arr.__len__() 是在 Python 中获取数组长度的首选方法吗? [英] Is arr.__len__() the preferred way to get the length of an array in Python?
问题描述
在Python中,以下是获取数量的唯一方法元素?
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
同样适用于元组:
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
它是 故意这样做 以便列表、元组和其他容器类型或可迭代对象不需要都显式实现公共 .length()
方法,相反,您可以检查任何实现魔术"__len__()
方法的 len()
.
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.
当然,这似乎是多余的,但长度检查的实现可能会有很大差异,即使是在同一种语言中.经常看到一种集合类型使用 .length()
方法,而另一种类型使用 .length
属性,而另一种类型使用 .count()代码>.拥有语言级关键字统一了所有这些类型的入口点.因此,即使您可能不认为是元素列表的对象仍然可以进行长度检查.这包括字符串、队列、树等.
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.
len()
的函数性质也非常适合函数式编程风格.
The functional nature of len()
also lends itself well to functional styles of programming.
lengths = map(len, list_of_containers)
这篇关于arr.__len__() 是在 Python 中获取数组长度的首选方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!