Python - 计算列表中的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4130027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:22:46  来源:igfitidea点击:

Python - Count elements in list

pythonlist

提问by Bruce

I am trying to find a simple way of getting a count of the number of elements in a list:

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

MyList = ["a", "b", "c"]

I want to know there are 3 elements in this list.

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

回答by Ignacio Vazquez-Abrams

len()

len()

>>> someList=[]
>>> print len(someList)
0

回答by Srikar Appalaraju

just do len(MyList)

做就是了 len(MyList)

This also works for strings, tuples, dictobjects.

这也适用于strings, tuples,dict对象。

回答by winwaed

len(myList)should do it.

len(myList)应该这样做。

lenworks with all the collections, and strings too.

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

回答by Atul Arvind

len() 

it will count the element in the list, tuple and string and dictionary, eg.

它将计算列表、元组、字符串和字典中的元素,例如。

>>> 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

To learn Python you can use byte of python, it is best ebook for python beginners.

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

回答by user2373650

Len won't yield the total number of objects in a nested list (including multidimensional lists). If you have numpy, use size(). Otherwise use list comprehensions within recursion.

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

回答by Joyfulgrind

To find count of unique elements of list use the combination of len()and set().

为了找到列表使用的独特元素的组合的数量len()set()

>>> ls = [1, 2, 3, 4, 1, 1, 2]
>>> len(ls)
7
>>> len(set(ls))
4

回答by Abdul Majeed

You can get element count of list by following two ways:

您可以通过以下两种方式获取列表的元素数:

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


>>> l.__len__() 
3