列表中的Python计数元素

Bru*_*uce 245 python list

我试图找到一种简单的方法来获取列表中元素数量的计数:

MyList = ["a", "b", "c"]
Run Code Online (Sandbox Code Playgroud)

我想知道这个列表中有3个元素.

Ign*_*ams 367

len()

>>> someList=[]
>>> print len(someList)
0
Run Code Online (Sandbox Code Playgroud)

  • 我的IDE显示了一个list.count(...)内置,但它需要一个神秘的参数,没有返回正确的答案,并且很难找到它的文档. (2认同)
  • @ Reb.Cabin:https://docs.python.org/3/library/stdtypes.html#common-sequence-operations (2认同)

Sri*_*aju 93

做就是了 len(MyList)

这也适用于strings,tuples,dict的对象.


win*_*aed 47

len(myList) 应该这样做.

len 适用于所有集合和字符串!


Atu*_*ind 40

len() 
Run Code Online (Sandbox Code Playgroud)

它将计算列表中的元素,元组和字符串以及字典,例如.

>>> mylist = [1,2,3] #list
>>> len(mylist)
3
>>> word = 'hello' # string 
>>> len(word)
5
>>> vals = {'a':1,'b':2} #dictionary
>>> len(vals)
2
>>> tup = (4,5,6) # tuple 
>>> len(tup)
3
Run Code Online (Sandbox Code Playgroud)

要学习Python你可以使用python的字节,它是python初学者的最佳电子书.


Joy*_*ind 25

要查找列表的独特元素的计数使用的组合len()set().

>>> ls = [1, 2, 3, 4, 1, 1, 2]
>>> len(ls)
7
>>> len(set(ls))
4
Run Code Online (Sandbox Code Playgroud)


Abd*_*eed 10

你可以通过以下两种方式获得列表的大小.

>>> l = ['a','b','c']
>>> len(l)
3

OR

>>> l.__len__() 
3
Run Code Online (Sandbox Code Playgroud)


小智 9

Len不会产生嵌套列表中的对象总数(包括多维列表).如果有numpy,请使用size().否则在递归中使用列表推导.