はthe right wayで始めることができます:
popular = ['red', 'blue', 'green', 'red', 'yellow',
'red', 'blue', 'red', 'yellow']
from collections import Counter
c = Counter(popular)
# lists the elements and how often they appear
print c.most_common()
# -> [('red', 4), ('blue', 2), ('yellow', 2), ('green', 1)]
@spidee:あなたが言及すると、「トレンド」私はあなたが最後の1000(またはそう)色を見て、どれが最もているかを確認したいという意味を推測一般?
あなたの周りの最後のアイテムを保持し、それらをカウントするカウンタを更新するために、(それはリストのようなものだ)dequeue
を使用することができます。
from collections import Counter, deque
def trending(seq, window=1000, n=5):
""" For every item in `seq`, this yields the `n` most common elements.
Only the last `window` elements are stored and counted """
c = Counter()
q = deque()
it = iter(seq)
# first iterate `window` times:
for _ in xrange(window):
item = next(it) # get a item
c[item]+=1 # count it
q.append(item) # store it
yield c.most_common(n) # give the current counter
# for all the other items:
for item in it:
drop = q.popleft() # remove the oldest item from the store
c[drop] -=1
if c[drop]==0:
# remove it from the counter to save space
del c[drop]
# count, store, yield as above
c[item] +=1
q.append(item)
yield c.most_common(n)
for trend in trending(popular, 5, 3):
print trend
なぜそれはリストでなければならないのですか?それは間違ったツールです... –
私はすべての選択肢を保存する様々なソリューションを見てきました - 何が思い出されるようですが、リストにはすべての選択肢が保存されていなかったソリューションがありました。だから、10トレンドの色をストアすることができました。しかし、私は私がredbullを夢見ているかもしれないと言った。 – spidee
上記のコメントが表示されても、理由はありません。すべての選択内容を保存するケースではありませんでした。 – spidee