python获取列表中某个元素个数_如何获取列表中的元素数?

How to get the size of a list?

要查找列表的大小,请使用内置函数len:items = []

items.append("apple")

items.append("orange")

items.append("banana")

现在:len(items)

返回3。

解释

Python中的所有内容都是一个对象,包括列表。在C实现中,所有对象都有某种类型的头。

在Python中,列表和其他类似的具有“size”的内置对象有一个名为ob_size的属性,其中缓存了对象中的元素数。所以检查列表中的对象数量非常快。

len(s)Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or

a collection (such as a dictionary, set, or frozen set).

len由数据模型docs中的__len__实现:

object.__len__(self)Called to implement the built-in function len(). Should return the length of the object, an integer >= 0. Also, an object that doesn’t

define a __nonzero__() [in Python 2 or __bool__() in Python 3] method and whose __len__() method returns zero

is considered to be false in a Boolean context.

我们还可以看到__len__是一种列表方法:items.__len__()

返回3。

内置类型可以获得

事实上,我们可以得到所有描述类型的信息:>>> all(hasattr(cls, '__len__') for cls in (str, bytes, tuple, list,

xrange, 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!

...

简而言之,if items或if not items可读性和性能都更高。

你可能感兴趣的:(python获取列表中某个元素个数_如何获取列表中的元素数?)