如何获取列表的大小?
要查找列表的大小,请使用内置函数len:
items = []
items.append("apple")
items.append("orange")
items.append("banana")
现在:
len(items)
返回 3。
说明
Python 中的一切都是对象,包括列表。所有对象在 C 实现中都有某种标题。
Python 中具有“大小”的列表和其他类似的内置对象,特别是有一个名为ob_size 的属性,其中缓存了对象中的元素数量。因此检查列表中的对象数量非常快。
但是,如果您要检查列表大小是否为零,请不要使用 len - 而应使用 put the list in a boolean context - it treated as False if empty, True otherwise。
len(s)
返回对象的长度(项目数)。参数可以是一个序列(例如字符串、字节、元组、列表或范围)或
集合(例如字典、集合或冻结集合)。
len 是用__len__ 实现的,来自数据模型docs:
object.__len__(self)
调用以实现内置函数len()。应该返回对象的长度,一个整数 >= 0。另外,一个不
定义一个 __nonzero__() [在 Python 2 中或在 Python 3 中的 __bool__()] 方法并且其 __len__() 方法返回零
在布尔上下文中被认为是错误的。
我们还可以看到__len__是一个列表方法:
items.__len__()
返回 3。
你可以得到len(长度)的内置类型
事实上,我们看到我们可以获得所有描述类型的信息:
>>> all(hasattr(cls, '__len__') for cls in (str, bytes, tuple, list,
range, dict, set, frozenset))
True
不要使用len 来测试空或非空列表
要测试特定长度,当然,只需测试相等性:
if len(items) == required_length:
...
但是有一种特殊情况可以测试零长度列表或相反的列表。在这种情况下,不要测试相等性。
另外,不要这样做:
if len(items):
...
相反,只需这样做:
if items: # Then we have some items, not empty!
...
或
if not items: # Then we have an empty list!
...
我 explain why here 但简而言之,if items 或 if not items 更具可读性和性能。