2017-02-22 12 views
0

いつでも最も多くの人数を持つ月を見つける必要があります。私が書いたコードは、だけではなく、その日Pythonのネストされた辞書

def total_days(birthdays): 
    ''' 
    >>> total_days({"Jan": {2: ["Ben"], 3: ["Sarah"], 6: ["Rob"]}, 
    "Feb": {1: ["Jimmy", "Timmmy"], 30: ["Sam", "Tony"]}}) 

    'Feb' 

    ''' 
    total = 0 
    month = '' 
    for i in birthdays: 
     new = len(birthdays[i]) 
     if new > total: 
      total = new 
      month = i 
    return month 

2月には2を持っていながら、月に3つの日付があるので、このコードは、月を返すの誕生日を持っているどのように多くの人々の日々の中で最も量を探しますが、私は月に必要2月

あるべき人々のほとんどの量と感謝

+0

を試してみてくださいに役立ちます願っています。 – spicypumpkin

+0

私は考えましたが、正しく動作させる方法がわかりません – Patrick

答えて

1

あなたはただ1つのforループより深く行く必要があります。あなたのコードはすぐにループのためのあなたの最初の後を除いて、完璧で、追加:

​​
+0

ありがとうございました – Patrick

+0

もしそうなら、私の答えを正しいものとして受け入れてください! –

0

このコードはbusiest_monthに結果を格納します。

busiest_month = None 
busiest_day_overall = None, 0 
for month in birthdays: 
    busiest_day_in_month = max([(day, len(people)) for day, people in birthdays[month].items()]) 
    if busiest_day_in_month[1] > busiest_day_overall[1]: 
     busiest_month = month 
0

1つのライナー:

from collections import Counter 
birthdays = {"Jan": {2: ["Ben"], 3: ["Sarah"], 6: ["Rob"]}, 
      "Feb": {1: ["Jimmy", "Timmmy"], 30: ["Sam", "Tony"]}} 

Counter({month: sum(len(names) for names in dates.values()) for (month, dates) in birthdays.items()}).most_common(1)[0][0] 

(まあ、OK、技術的にはそこにいくつかの行がある)

それは(辞書内包表記は、これはのみ動作します意味辞書とリスト内包表記を使用していますPython 2.7以降)。基本的には、日付/名前のリストを1つの値(日付に付けられた名前の数)に集約し、それを月ごとに合計します。 collections.Counterを使用して最高スコアリングされた要素を見つける。

0

この

def total_days(birthdays): 
    total = 0 
    month = '' 
    for i,j in birthdays.viewitems(): 
     new =j.keys() 
     new.sort() 
     if total < new[-1]: 
      total = new[-1] 
      month = i 
    return month 

で試してみてください、それが

0

は一つの簡単な解決策は、ネストされた `for`ループを使用することです

birthdays={"Jan": {2: ["Ben"], 3: ["Sarah"], 6: ["Rob"]}, 
      "Feb": {1: ["Jimmy", "Timmmy"], 30: ["Sam", "Tony"]}} 
yourData=[(mon,max([len(p) for d,p in day.iteritems()])) for mon,day in birthdays.iteritems()] 
print [i[0] for i in yourData if i[1]==max(map(lambda x: x[1], yourData))][0] 
関連する問題