简体   繁体   中英

How to find number of instances of an item in a python list

I want to part of a script to be something like this.

if list[1] is in list.pop n times:
      return True

Simply use:

list.count(element)

Example:

>>> [1,2,3,4,2,1].count(1)
2

Number of items in a list:

len(myList)

Number of times the i th element occurs in a list:

myList.count(mylist[i])

Or you can use Counter :

>>> from collections import Counter
>>> Counter([1, 2, 3, 1, 1])
Counter({1: 3, 2: 1, 3: 1})
>>> 

This is good if you want to get all the counts of the distinct elements in the list one time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM