有很多不同的方法來實現這一點。第一種,也可能是最簡單的,是從collections
導入Counter
類。
from collections import Counter
ages = [20,20,11,12,10,11,15]
counts = Counter(ages)
# Counter({10: 1, 11: 2, 12: 1, 15: 1, 20: 2})
# if you want to strictly be a dictionary you can do the following
counts = dict(Counter(ages))
的另一種方法是做一個循環:
counts = {}
for a in ages:
# if the age is already in the dicitonary, increment it,
# otherwise, set it to 1 (first time we are seeing it)
counts[a] = counts[a] + 1 if a in counts else 1
最後,dict comprehension。除了它是一條線以外,它在循環中沒有任何優勢。你還是最終列表中的遍歷每個變量:
counts = {a:ages.count(a) for a in ages}
既然你問更多有關ternary operator,這個循環就等於說:
counts = {}
for a in ages:
# if the age is already in the dicitonary, increment it,
# otherwise, set it to 1 (first time we are seeing the number)
if a in counts:
counts[a] = counts[a] + 1
print("Already seen", a, " -- ", counts[a])
else:
counts[a] = 1
print("First time seeing", a, " -- ", counts[a])
三元運算符可以讓我們在一行中完成此模式。語言很多有它:
- C/C++/C#
- JavaScript
可以使用計數器它https://docs.python.org/3/library/collections.html#collections.Counter – AndMar
謝謝你,但我手動試圖做到這一點,而不庫 – MAUCA