私は次のプログラムからソートされた出力を取得しようとしています。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]
あなたは私が最善の方法を教えてくださいだろうか?
これらは変更不可ですが、並べ替え可能です。辞書の配列部分だけを使用しない限り、辞書はここには当てはまりません。または、質問をすべて変更した場合しかし、リストはオプションになります。 –
あなたは上記のコードの変更を提案して、希望の出力を与えることができます –
ローカルエディタで '(、)' –