有很多不同的方法来实现这一点。第一种,也可能是最简单的,是从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