python - 如何检查输入是否在数组中并打印另一个数组的相应元素?
问题描述
如果我正在制作一个“翻译器”并且为每个字母分配一个世界(例如 cat = a,dog = b ...),我可以只制作 2 个数组,其中第一个数组中每个字母的“翻译”例如对应于另一个数组中与字母本身位置相同的元素
array_1 = ["a", "b"]
array_2 = ["cat", "dog"]
def translation(phrase):
translation = ""
for letter in phrase:
if letter in array_1:
translation += #the element of array_2 in the same position of the element of array_1 witch is equal to letter
return translation
print(translation(input()))
解决方案
您可以使用两个列表。但是,更好的解决方案是使用字典值。这样,您只需输入一个键(输入词)并获得它转换为的值。你可以使用这个:
dictionary = { 'a': 'cat', 'b' : 'dog'}
并且可以轻松地添加更多的翻译形式,input : output
以便更轻松地查看每个输入的翻译内容。然后翻译一个单词的方法是,对于每个输入,键入
dictionary[input]
你会得到正确的输出。例如,dictionary['a']
将'cat'
在本例中返回。这减少了计算每个键和输出在每个列表中的位置以确保它们匹配的时间。
要连续翻译多个字符,请使用以下命令:
dictionary = { 'a': 'cat', 'b' : 'dog'}
undecoded="abbabaa"
decoded=""
for i in undecoded:
decoded=decoded+dictionary[i]
print(decoded)
希望这可以帮助!-西奥
编辑:正如 juanpa.arrivillaga 所提到的,如果您已经有两个要转换为字典形式的列表,则可以使用dictionary=dict(zip(array_1, array_2))
推荐阅读
- ffmpeg - ffmpeg 流输入 sdp 显示警告关键帧丢失
- python - 无法训练预训练模型 (EfficientNet)
- flutter - Flutter 如何在另一个页面上的点击事件中从 ListTile 恢复数据
- git - 回购命令无法识别
- reactjs - Material-UI 从 DataGrid 获取所有行
- image-processing - 我怎样才能提高yolov5的训练结果
- npm - 当在 ky.Post api(KY npm 包)中添加 OnDownloadProgress 事件时,响应标头已损坏
- python - 是否可以从 Counter() Python 中获取二进制计数
- c++ - 为什么 GRPC 会生成模板类?
- javascript - 如何在反应中为我的输入添加条件?