首页 > 解决方案 > 如何检查输入是否在数组中并打印另一个数组的相应元素?

问题描述

如果我正在制作一个“翻译器”并且为每个字母分配一个世界(例如 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()))

标签: python

解决方案


可以使用两个列表。但是,更好的解决方案是使用字典值。这样,您只需输入一个键(输入词)并获得它转换为的值。你可以使用这个:

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))


推荐阅读