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
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屋!