まず、貼り付けたコードは実行されません。関数定義にアンダースコアの代わりにスペースがあり、何も返されません。
しかし、それを修正した後、コードはまさにあなたが記述したとおりに動作します。
理由を理解するには、 s を追加して各ステップでの動作を確認するか、このprint
ようなビジュアライザーで実行してみてください。
y
isのポイントに到達すると、次のようになり"we"
ます。
string = string.replace("we", "you")
しかし、それは のすべて we
を置き換えstring
ますwent
。
このようにしたい場合は、おそらく次のように のそれぞれを変更y
し、最後list
にjoin
それらを元に戻す必要があります。
def random_sentence(sentence):
list = sentence.split()
for index, y in enumerate(list):
for i in words:
for u in i:
if y == u:
mylist = i[1]
list[index] = mylist
return ' '.join(list)
これを理解するのが難しいと思うなら、私もそうです。すべての変数名は、1 文字か、誤解を招くような名前です (たとえばmylist
、リストでさえありません)。また、i
本当に最初の要素だけをチェックしたい場合は、見ています。これが読みやすいかどうかを確認します。
replacements = [["I", "you"], ["i", "you"], ["we", "you"], ["my", "your"], ["our", "your"]]
def random_sentence(sentence):
words = sentence.split()
for index, word in enumerate(words):
for replacement in replacements:
if word == replacement[0]:
words[index] = replacement[1]
return ' '.join(words)
ただし、この問題を解決するためのはるかに優れた方法があります。
まず、単語と置換のペアのリストを用意する代わりに、辞書を使用します。次に、ループ全体を取り除き、読みやすくします (さらに高速化します)。
replacements = {"I": "you", "i": "you", "we": "you", "my": "your", "our": "your"}
def random_sentence(sentence):
words = sentence.split()
for index, word in enumerate(words):
replacement = replacements.get(word, word)
words[index] = replacement
return ' '.join(words)
そして、元のリストをその場で変更しようとする代わりに、新しいリストを作成してください:
def random_sentence(sentence):
result = []
for word in sentence.split():
result.append(replacements.get(word, word))
return ' '.join(result)
次に、これresult = []
はfor …: result.append(…)
まさにリスト内包表記の目的です。
def random_sentence(sentence):
result = [replacements.get(word, word) for word in sentence.split()]
return ' '.join(result)
…または、実際にはリストを必要としないため、join
代わりにジェネレーター式を使用できます。
def random_sentence(sentence):
return ' '.join(replacements.get(word, word) for word in sentence.split())