我正在尝试从列表中检索单词;我要求用户输入一个列表中的一个单词,然后我想在该列表中找到该单词的位置,例如,
list = ["a", "b", "c", "d"]
list2 = [1,2,3,4]
使用这些列表,如果用户输入“a”,那么计算机计算出它是列表中的第一个字符串并从list2中选出“1”,或者如果它们输入“c”,则它会找到“3” ”。但是,由于名单经常扩大和缩小,我不能使用:
if input == list[0]:
variable = list2[0]
etc
我尝试过:
y = 0
x = 1
while x == 1:
if input == list[y]:
variable = list2[y]
x = 2
else:
y = y + 1
但这不起作用,那么无论如何都可以做到这一点?或者我是一个蒙面而且错过了明显的......
答案 0 :(得分:0)
list1 = ["a", "b", "c", "d"]
list2 = [1,2,3,4]
needle = "c"
for item1, item2 in zip(list1, list2):
if item1 == needle:
print(item2)
答案 1 :(得分:0)
这可能是最简单的解决方案:
>>> list1 = ["a", "b", "c", "d"]
>>> list2 = [1, 2, 3, 4]
>>>
>>> mapping = dict(zip(list1, list2))
>>>
>>> mapping['b']
2
顺便说一句,要了解发生了什么:
>>> zip(list1, list2)
[('a', 1), ('b', 2), ('c', 3), ('d', 4)]
>>> dict(zip(list1, list2))
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
无论如何,你问过如何在列表中获取索引。使用index
:
>>> list1.index('c')
2
然后:
>>> list2[list1.index('c')]
3
另外......不要为您的列表list
命名,因为这样您就可以“隐藏”内置list
。
答案 2 :(得分:0)
这是我认为你想要完成的一个简单版本:
a = ['a', 'b', 'c', 'd']
b = [1, 2, 3, 4]
ret = input("Search: ")
try:
idx = a.index(ret)
print(b[idx])
except ValueError:
print("Item not found")
答案 3 :(得分:0)
list1 = ["a", "b", "c", "d"]
list2 = [1,2,3,4]
x = input()
if x in list1 :
print list2[list1.index(x)]
else :
print "Error"