キーが単語の長さで、値が単語自体である辞書を返すコーディング演習を続けています。これは、get_word_len_dict(text)関数に渡されるパラメーターであるテキストを分割し、文字数をカウントすることによって行われます。次に、長さがソートされ、print_dict_in_key_order(a_dict)に出力されます。
次のような出力が得られます。
2 : ['to', 'is']
3 : ['why', 'you', 'say', 'are', 'but', 'the', 'wet']
4 : ['does', 'when', 'four', 'they', 'have']
5 : ['there', 'stars', 'check', 'paint']
7 : ['someone', 'believe', 'billion']
どちらが正しいように見えますが、リスト内の値をアルファベット順に並べたい場合はどうなりますか?つまり、大文字で始まる単語も優先する必要があります。例えば。['5月'、 'および']。
理想的には、アルファベット順の値で次のような出力が必要です。
2 : ['is', 'to']
3 : ['are', 'but', 'say', 'the', 'wet', 'why', 'you']
4 : ['does', 'four', 'have', 'they', 'when']
5 : ['check', 'paint', 'stars', 'there']
7 : ['believe', 'billion', 'someone']
これまでprint_dict_in_key_order(a_dict)内でキーを並べ替えることができましたが、値も並べ替えたい場合はどうすればよいかわかりませんか?
def get_word_len_dict(text):
dictionary = {}
word_list = text.split()
for word in word_list:
letter = len(word)
dictionary.setdefault(letter,[])
if word not in dictionary[letter]:
dictionary[letter].append(word)
return dictionary
def test_get_word_len_dict():
text = 'why does someone believe you when you say there are four billion stars but they have to check when you say the paint is wet'
the_dict = get_word_len_dict(text)
print_dict_in_key_order(the_dict)
def print_dict_in_key_order(a_dict):
all_keys = list(a_dict.keys())
all_keys.sort()
for key in all_keys:
print(key, ":", a_dict[key])
あなたがしたいことは、長さでグループ化し、次に値でソートし(辞書式順序で比較すると大文字は小文字よりも「小さい」ため)、各グループから重複を削除し、すべてをdict
理解することです。
itertools.groupby
たとえば、の類似関数とは異なりpandas
、は隣接しないグループを別個のものとして扱うため、最初に長さで並べ替える必要があることに注意してください。
例:
from itertools import groupby
from pprint import pprint
def solution(sentence):
sorted_words = sorted(sentence.split(' '), key=len)
return {length: sorted(set(words)) for length, words in groupby(sorted_words, len)}
sentence = 'Why does someone believe you when you say there are four billion stars but they have to check when you say the paint is wet'
pprint(solution(sentence))
出力:
{2: ['is', 'to'],
3: ['Why', 'are', 'but', 'say', 'the', 'wet', 'you'],
4: ['does', 'four', 'have', 'they', 'when'],
5: ['check', 'paint', 'stars', 'there'],
7: ['believe', 'billion', 'someone']}
'Why'
大文字で始まり、残りはアルファベット順にソートされているため、他の文字よりも前に来ることに注意してください。
関数構造を保持したい場合list
は、辞書でそれぞれをインプレースで並べ替えることができます。
def get_word_len_dict(text):
dictionary = {}
word_list = text.split()
for word in word_list:
letter = len(word)
dictionary.setdefault(letter,[])
if word not in dictionary[letter]:
dictionary[letter].append(word)
for words in dictionary.values():
words.sort()
return dictionary
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加