python读取数组长度,arr .__ len __()是在Python中获取数组长度的首选方法吗?

博客讨论了Python中获取元素数量的方式,指出除了使用`__len__()`方法,更推荐用`len()`函数。该函数适用于列表、元组、字符串等多种类型,统一了不同类型的长度检查入口,且其功能性适合函数式编程风格。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

In Python, is the following the only way to get the number of elements?

arr.__len__()

If so, why the strange syntax?

解决方案my_list = [1,2,3,4,5]

len(my_list)

# 5

The same works for tuples:

my_tuple = (1,2,3,4,5)

len(my_tuple)

# 5

And strings, which are really just arrays of characters:

my_string = 'hello world'

len(my_string)

# 11

It was intentionally done this way so that lists, tuples and other container types or iterables didn't all need to explicitly implement a public .length() method, instead you can just check the len() of anything that implements the 'magic' __len__() method.

Sure, this may seem redundant, but length checking implementations can vary considerably, even within the same language. It's not uncommon to see one collection type use a .length() method while another type uses a .length property, while yet another uses .count(). Having a language-level keyword unifies the entry point for all these types. So even objects you may not consider to be lists of elements could still be length-checked. This includes strings, queues, trees, etc.

The functional nature of len() also lends itself well to functional styles of programming.

lengths = map(len, list_of_containers)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值