이렇게하려면 여러 가지 방법이 있습니다. 가장 쉬운 방법은 Counter
클래스를 collections
에서 가져 오는 것입니다.
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 = {}
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])
삼항 연산자는 우리를 할 수 있습니다 : 당신이 ternary operator에 대한 자세한 내용을 요구하기 때문에
counts = {a:ages.count(a) for a in ages}
, 그 루프는 말에 해당합니다 이 패턴을 한 줄로 완성하십시오. 언어의 제비가있다 :
- C/C++/C#
- JavaScript
당신은 https://docs.python.org/3/library/collections.html#collections.Counter – AndMar
이 감사에 대한 카운터를 사용할 수 있지만, 나는 도서관 – MAUCA