获得了一个Python数组的长度 [英] Getting the length of an array in Python

查看:583
本文介绍了获得了一个Python数组的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python中,是下面的唯一途径获得的元素个数?

 改编.__ LEN __()

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


解决方案

  MYLIST = [1,2,3,4,5]
LEN(MYLIST)

元组相同的作品:

  mytuple =(1,2,3,4,5)
LEN(mytuple)

这是<一个href=\"http://effbot.org/pyfaq/why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list.htm\">intentionally做这样使列表,元组和其他容器类型并不都需要明确公开实施。长度()方法,而你可以检查在 LEN()的任何实现的魔力 __ __ LEN()方法。

当然,这看起来是多余的,但长度检查实现可以即使在同一语言相当大的变化。这不是经常看到一个集合类型使用。长度()方法,而另一种使用。长度属性,而另一个使用 .Count之间的()。具有语言级的关键字统一所有这些类型的入口点。因此,即使对象你可能不认为是元素的列表可能仍然是长度检查。这包括字符串,队列,树等。

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

arr.__len__()

If so, why the strange syntax?

解决方案

mylist = [1,2,3,4,5]
len(mylist)

The same works for tuples:

mytuple = (1,2,3,4,5)
len(mytuple)

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.

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.

这篇关于获得了一个Python数组的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆