我有两个命名A和B的列表:
A = ["boy","girl","place","food"]
B = ["he","she","USA,UK","Pizza,Burger,Sushi"]
当用户输入“boy”时,我希望输出为“he”。简而言之,我希望列表A中元素的索引值被赋予列表B中相同索引的值。
A[0] == B[0]
A[1] == B[1]
A[2] == B[2]
A[3] == B[3]
这就是我想要的。如果我输入A [i]中给出的数据,输出应该是B [i]中给出的。谢谢。
答案 0 :(得分:2)
您可以使用.index(input_string)
检索用户输入的索引,然后调用B:
A = ["boy","girl","place","food"]
B = ["he","she","USA,UK","Pizza,Burger,Sushi"]
i = A.index('boy')
print B[i] # he
我认为您需要考虑将 dict 合并到这些列表中。
my_dict = dict(zip(A, B))
user_input = raw_in-put('enter a word\n')
if user_input in my_dict:
print my_dict[user_input]
答案 1 :(得分:0)
我可以使用额外的字典将A的值作为B值的键。
请查看以下示例以获取更多参考资料
A = ["boy","girl","place","food"]
B = ["he","she","USA,UK","Pizza,Burger,Sushi"]
dic = zip(A, B)
print(dic["boy"])
希望这有帮助!
答案 2 :(得分:0)
首先,您必须检查您的输入是否确实在A中。然后,如果是,使用index
方法找到A中项目的索引,则使用它访问B.
A = ["boy","girl","place","food"]
B = ["he","she","USA,UK","Pizza,Burger,Sushi"]
input_string = 'place'
if input_string in A:
output_string = B[A.index(input_string)]
print(output_string) # outputs 'USA,UK'
答案 3 :(得分:0)
理想情况下,您将数据构建为列表列表,因为就像现在一样,在不知道需要哪些组的情况下格式化字典非常困难:
A = ["boy","girl","place","food"]
B = ["he","she",["USA,UK"],["Pizza,Burger,Sushi"]]
new_data = {a:b for a, b in zip(A, B)}
print(new_data["boy"])
输出:
"he"
答案 4 :(得分:0)
你绝对想要一个字典。
a_to_b = dict(zip(a,b))
print a_to_b['he'] == 'boy'
for key in a:
print key, a_to_b[key]