Python 在列表中查找变量
我试图从列表中检索一个单词;我要求用户输入一个单词,它是列表的一部分,然后我想找到该单词在该列表中的位置,例如Python 在列表中查找变量,python,list,python-3.x,Python,List,Python 3.x,我试图从列表中检索一个单词;我要求用户输入一个单词,它是列表的一部分,然后我想找到该单词在该列表中的位置,例如 list = ["a", "b", "c", "d"] list2 = [1,2,3,4] 在这些列表中,如果用户输入“a”,那么计算机计算出它是列表中的第一个字符串,并从列表2中选择“1”,或者如果用户输入“c”,那么计算机会找到“3”。但是,由于列表经常扩展和缩小,我无法使用: if input == list[0]: variable = list2[0] etc 我
list = ["a", "b", "c", "d"]
list2 = [1,2,3,4]
在这些列表中,如果用户输入“a”,那么计算机计算出它是列表中的第一个字符串,并从列表2中选择“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
但这不起作用,所以无论如何,这是可以做到的吗?还是我是一个蒙古人,错过了显而易见的…选项1
list1 = ["a", "b", "c", "d"]
list2 = [1,2,3,4]
needle = "c"
for item1, item2 in zip(list1, list2):
if item1 == needle:
print(item2)
这可能是最简单的解决方案:
>>> 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}
选择2
不管怎样,您询问了如何在列表中获取索引。使用索引
:
>>> list1.index('c')
2
然后:
>>> list2[list1.index('c')]
3
还有。。。不要给列表命名,因为这样你就“隐藏”了内置的
列表
以下是我认为你试图实现的一个简单版本:
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")
看起来您可以使用一个存储映射的字典。同时,隐藏内置名称
列表是个坏主意。还可以使用break
关键字,这样就可以完全去掉x
变量。列表有一个内置的索引方法
list1 = ["a", "b", "c", "d"]
list2 = [1,2,3,4]
x = input()
if x in list1 :
print list2[list1.index(x)]
else :
print "Error"