2016-07-17 14 views
2

私は次のプログラムからソートされた出力を取得しようとしています。Pythonでタプルを並べ替える

"""Count words.""" 
    # TODO: Count the number of occurences of each word in s 

    # TODO: Sort the occurences in descending order (alphabetically in case of ties) 

    # TODO: Return the top n words as a list of tuples 


from operator import itemgetter 
def count_words(s, n): 
    """Return the n most frequently occuring words in s.""" 

    t1=[] 
    t2=[] 
    temp={} 
    top_n={} 

    words=s.split() 
    for word in words: 
     if word not in temp: 
      t1.append(word) 
      temp[word]=1 
     else: 
      temp[word]+=1 
    top_n=sorted(temp.items(), key=itemgetter(1,0),reverse=True) 

    print top_n 

    return 


def test_run(): 
    """Test count_words() with some inputs.""" 
    count_words("cat bat mat cat bat cat", 3) 
    count_words("betty bought a bit of butter but the butter was bitter", 3) 


if __name__ == '__main__': 
    test_run() 

このプログラムの出力は次のようである:

[('cat', 3), ('bat', 2), ('mat', 1)] 

[('butter', 2), ('was', 1), ('the', 1), ('of', 1), ('but', 1), ('bought', 1), ('bitter', 1), ('bit', 1), ('betty', 1), ('a', 1)] 

が、私のような形式で必要があります。

[('cat', 3), ('bat', 2), ('mat', 1)] 

[('butter', 2), ('a', 1),('betty', 1),('bit', 1),('bitter', 1) ... rest of them here] 

あなたは私が最善の方法を教えてくださいだろうか?

+2

これらは変更不可ですが、並べ替え可能です。辞書の配列部分だけを使用しない限り、辞書はここには当てはまりません。または、質問をすべて変更した場合しかし、リストはオプションになります。 –

+0

あなたは上記のコードの変更を提案して、希望の出力を与えることができます –

+0

ローカルエディタで '()' –

答えて

3

はあなたがsortedに与えているkey機能を変更する必要が良いだろうあなたの望む出力内の項目は、降順にソートされる必要があるため、アルファベット順に昇順に並べ替える必要があります。昇順で並べ替えあなたの希望の順番を取得し、回数を否定することで

top_n = sorted(temp.items(), key=lambda item: (-item[1], item[0])) 

:私はlambda機能を使用すると思います。

+0

引数を渡してソートすることで返されるアイテムの数を制限できますか? –

+0

いいえ、 'sorted'は常にリスト全体をソートします。最初の 'n '値を取得するには、スライスを使用します:' top_n = top_n [:n] ' – Blckknght

0

あなたは変更することができます。

top_n=sorted(temp.items(), key=itemgetter(1,0),reverse=True) 

へ:

temp2=sorted(temp.items(), key=itemgetter(0),reverse=False) 
top_n=sorted(temp2.items(), key=itemgetter(1),reverse=True) 

Sort Stabilityのおかげであなたは

+0

ここでtemp2 shudを定義する方法は?このようにtemp2 = {} ?? –

+0

@ManishKumar最初の行はtemp2を定義し、seconedはそれを使用します。それを初期化する必要はありません。 –

0

代わりのitemgetterlambda t:(-t[1],t[0])を使用してreverse=Trueをドロップ:

top_n=sorted(temp.items(), key=lambda t:(-t[1],t[0])) 

これは高い数字が小さい番号の前にソートされるように反転された第1の値とitemgetter(1,0)と同じものを返します。

0
def count_words(s, n): 
"""Return the n most frequently occuring words in s.""" 

    t1=[] 
    t2=[] 
    temp={} 
    top_n={} 

    words=s.split() 
    for word in words: 
     if word not in temp: 
      t1.append(word) 
      temp[word]=1 
     else: 
      temp[word]+=1 
    top_n=sorted(temp.items(), key=lambda t: (t[1], t[0]),reverse=True) 

    print top_n 

    return 


def test_run(): 
"""Test count_words() with some inputs.""" 
    count_words("cat bat mat cat bat cat", 3) 
    count_words("betty bought a bit of butter but the butter was bitter", 3) 


if __name__ == '__main__': 
    test_run() 

私はlambdaの代わりitemgetterを使用して、私が書いた他のアプリでは、ラムダが動作しているようです。

関連する問題