且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用列表中的值替换列表中的单词

更新时间:2023-02-17 18:25:14

我不知道你为什么迭代每一个角色,每次分配 splitline 是一样的。我们不这样做。

I'm not sure why you're iterating over every character, assigning splitline to be the same thing every time. Let's not do that.

words = text.split()  # what's a splitline, anyway?

看起来你的术语倒退了,字典看起来像: {key:值} 不像 {value:key} 。在这种情况下:

It looks like your terminology is backwards, dictionaries look like: {key: value} not like {value: key}. In which case:

my_dict = {'the': 1, 'in': 2, 'a': 3}

是完美的转向男人住在房子里1人住2 3房

从那里你可以使用 dict.get 。我不推荐 str.replace

From there you can use dict.get. I don't recommend str.replace.

final_string = ' '.join(str(my_dict.get(word, word)) for word in words)
# join with spaces all the words, using the dictionary substitution if possible

dict.get 允许您指定默认值,如果该键不在字典中比起 dict [key] 提出一个 KeyError 。在这种情况下,您说的是给我键值,如果不存在,请给我

dict.get allows you to specify a default value if the key isn't in the dictionary (rather than raising a KeyError like dict[key]). In this case you're saying "Give me the value at key word, and if it doesn't exist just give me word"