次のようなリストがあります。
list1 = [1,2,4,6,8,9,2]
私が言うなら
if 2 in list1:
print True
True を 1 回出力します。2 または任意の変数 x がリストに複数回含まれているかどうかを判断する方法はありますか?
for item in list1:
if item = 2:
duplicates +=1
次のようなリストがあります。
list1 = [1,2,4,6,8,9,2]
私が言うなら
if 2 in list1:
print True
True を 1 回出力します。2 または任意の変数 x がリストに複数回含まれているかどうかを判断する方法はありますか?
for item in list1:
if item = 2:
duplicates +=1
あなたが探していると思いますlist.count
:
if list1.count(2) > 1:
print True
シーケンスタイプ:
s.count(i) s 内の i の総出現回数
もちろん、内部では、count
メソッドは全体を反復処理します(ただし、ループlist
よりもはるかに高速です)。for
パフォーマンス上の理由でそれを回避しようとしている場合、または の代わりに遅延反復子を使用できる場合は、list
他のオプションを検討することをお勧めします。たとえばsort
、リストと使用itertools.groupby
、またはそれをにフィードしますcollections.Counter
。
from collections import Counter
y = Counter(list1)
print y[2]
print y[5] # and so on
collections.Counter
これにはオブジェクトを使用します。
from collections import Counter
myCounter = Counter(list1)
print myCounter[2] > 1 #prints 'True'
ただし、リストの1つまたはいくつかの要素でのみこれを行うことを計画している場合は、abarnert's answerを使用します。
list1 = [1,2,4,6,8,9,2]
print list1.count(2)
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}
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]