2017-09-26 2 views
0

배열의 연령대를 반환하는 프로그램이 있는데이를 계산하여 사전에 넣고 싶습니다. 다음을 시도했습니다. 결과는 없습니다. 도와주세요!배열 내부의 값을 카운트하고 사전으로 변환하는 방법

는 이제 다음과 같이 내가 배열을 가정 해 봅시다 : 우리가 세트를 보면 같은

ages = [20,20,11,12,10,11,15] 
# count ages inside of array, I tried this 
for i in set(ages): 
    if i in ages: 
     print (ages.count(i)) 
# result returns the following 
    1 
    2 
    1 
    1 
    2 

이 완벽 의미가 있습니다 (연령)은 = {1011121520}

동일

그래서 돌아 오는 계산은 실제로 각 값의 수와 같습니다.

변수를 넣으려고하면 첫 번째 숫자 만 추가되거나 iterable이 아니라고합니다! 어떻게 더 나은 내가 사전 세트의 각 세트 (나이)와 수를 포함하는 (나이를) 만들 수있는 방법

+0

당신은 https://docs.python.org/3/library/collections.html#collections.Counter – AndMar

+0

이 감사에 대한 카운터를 사용할 수 있지만, 나는 도서관 – MAUCA

답변

1

이렇게하려면 여러 가지 방법이 있습니다. 가장 쉬운 방법은 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} 

, 그 루프는 말에 해당합니다 이 패턴을 한 줄로 완성하십시오. 언어의 제비가있다 :

  1. C/C++/C#
  2. JavaScript
+0

좋은하지 않고 수동으로 할 노력하고 있어요! 질문이 있습니다. 변수를 설정할 때 if 및 else 문을 어떻게 사용할 수 있습니까? – MAUCA

+0

이것은 [삼항 연산자]라고 불립니다. (http://pythoncentral.io/one-line-if-statement-in-python-ternary-conditional-operator/) 코드의 일부 라인을 자유롭게 만듭니다. 'count in : counts [a] = [a] + 1 else : counts [a] = 1'을 수행하는 것과 같습니다. – TheF1rstPancake

+1

'콜렉션에서 카운터 가져 오기 '가 유효하지 않은 구문입니까? – mentalita

2

이 시도 감사합니다,리스트로 저장할 수 있습니다!

ages = [20,20,11,12,10,11,15] 
dic = {x:ages.count(x) for x in ages} 
print dic 
0

당신이 수를 저장해야하는 경우, 당신은 파이썬 dicts을 사용하여 더 나은.

ages = [20,20,11,12,10,11,15] 
age_counts={} #define dict 
for i in ages: 
    #if age_counts does not have i, set its count to 1 
    #increment otherwise 
    if not age_counts.has_key(i): 
     age_counts[i]=1 
    else: 
     age_counts[i]+=1 
#you can now have counts stored 
for i in age_counts: 
    print i, age_counts[i] 
관련 문제