Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

python - arr .__ len __()是获取Python数组长度的首选方法吗?(Is arr.__len__() the preferred way to get the length of an array in Python?)

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

(在Python中 ,以下是获取元素数量的唯一方法吗?)

arr.__len__()

If so, why the strange syntax?

(如果是这样,为什么奇怪的语法?)

  ask by Joan Venge translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...