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 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()
方法,而是只需检查实现'magic' __len__()
的任何东西的len()
__len__()
方法。)
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()
. (这不是经常看到一个集合类型使用.length()
方法,而另一种类型的使用.length
属性,而另一个使用.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.
(len()
的功能特性也很适合函数式编程。)
lengths = map(len, list_of_containers)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…