我有一个如下所示的列表:
list1 = [1,2,4,6,8,9,2]
如果我要说
if 2 in list1:
print True
它打印True一次。有没有办法确定2或任何变量x是否多次出现在列表中,如果有,有多少没有像这样迭代整个列表?
for item in list1:
if item = 2:
duplicates +=1
答案 0 :(得分:7)
我认为你正在寻找list.count
:
if list1.count(2) > 1:
print True
s.count(i)s中出现的总数
当然,在count
方法中,list
方法将遍历整个for
(尽管它会比list
循环快得多)。如果您出于性能原因而试图避免这种情况,或者您可以使用惰性迭代器而不是sort
,则可能需要考虑其他选项。例如,itertools.groupby
列表并使用collections.Counter
,或将其提供给{{1}}等。
答案 1 :(得分:4)
from collections import Counter
y = Counter(list1)
print y[2]
print y[5] # and so on
答案 2 :(得分:1)
list1 = [1,2,4,6,8,9,2]
print list1.count(2)
答案 3 :(得分:1)
我会使用collections.Counter
对象:
from collections import Counter
myCounter = Counter(list1)
print myCounter[2] > 1 #prints 'True'
如果您只计划使用列表中的一个或几个元素执行此操作,我会选择abarnert's answer。
答案 4 :(得分:0)
Collections.counter(正如其他人指出的那样)是我如何做到的。但是,如果你真的想弄清楚:
def count(L):
answer = {}
for elem in L:
if elem not in answer:
answer[elem] = 0
answer[elem] += 1
return answer
>>> counts = count(myList)
>>> duplicates = [k for k,v in counts.iteritems() if v>1]
答案 5 :(得分:0)
list1 = [1,2,4,6,8,9,2]
dict1 = {}
for ele in list1:
# you iterate through the list once
if ele in dict1:
# if a key is already in the dictionary
# you increase the corresponding value by one
dict1[ele] += 1
else:
# if a key is not yet in the dictionary
# you set its corresponding value to one
dict1[ele] = 1
结果:
>>> dict1
{1: 1, 2: 2, 4: 1, 6: 1, 8: 1, 9: 1}