我希望用户可以输入数字,并且如果数字与列表值匹配,那么程序将返回输入的值及其索引。
我该怎么做? 我已经写了一些代码,但是没有用。...
a = [10, 20, 30, 40, 50, 60]
inp = int(input("Enter digit"))
i =0
for i in a:
if inp == a[i]:
print("You found it {}".format(a[i]))
else:
print("No found")
它正在引发IndexError。
答案 0 :(得分:1)
for i in a
遍历a
的元素,而不是其整数索引。
您可以使用enumerate
来修改代码。
a = [10, 20, 30, 40, 50, 60]
inp = int(input('Enter digit: '))
for index, value in enumerate(a):
if value == inp:
print('You found it at position {}'.format(index))
break
else: # no break
print('not found')
另外,我更改了 string input('Enter digit: ')
返回到int
和break
,一旦看到目标一次,就会退出循环。
有关如何在编程练习之外对此行为进行编程的解决方案,请参见this question。
答案 1 :(得分:0)
更改
for i in a:
if inp == a[i]:
...
到
for i in a:
if inp == i:
...
因为for
循环遍历列表中的元素(而不是遍历索引)
答案 2 :(得分:0)
您必须使用
1 0
2 0
将for i in range(len(a)):
循环构造为for
会引起索引错误,这意味着for i in a
将遍历i
的内容。然后调用a
将不起作用,因为在循环的第一步中,您正在调用a[i]
。
或者,您可以像这样直接遍历a[10]
的元素:
a
会将用户输入内容与for a_element in a:
if inp == a_element:
的内容进行比较。
答案 3 :(得分:0)
我认为不需要for循环:
l = [i for i in range(0,100,10)]
def found_it():
print("You found it {}".format(l.index(ans)))
if ans in l:
print("You found it")
else:
print("Try again")
found_it()
答案 4 :(得分:0)
a = [10, 20, 30, 40, 50, 60]
inp = int(input("Enter digit: "))
if inp in a:
print("You found {} at {}".format(inp, a.index(inp)))
else:
print("Not found")
答案 5 :(得分:0)
更多的pythonic方式是:
a = [10, 20, 30, 40, 50, 60]
inp = int(input("Enter digit :"))
if inp in a:
print "You found", inp, "at index:", a.index(inp)
else:
print "Not found"
输出:
Enter digit :10
You found 10 at index: 0
答案 6 :(得分:0)
首先,在整数列表中找到用户输入之前,始终使用int()函数将其转换为整数。
我想您只需要查找列表中是否存在一个元素,为此,您可以尝试以下操作:
a = [10, 20, 30, 40, 50, 60]
inp = int(input("Enter digit"))
if inp in a:
print("You found it at index {}".format(a.index(inp)))
else:
print("Not found")
答案 7 :(得分:0)
代码中存在一些逻辑错误:
输入函数返回字符串值,您正在比较 带有数组int值的字符串值'inp'。需要输入 值。
对于a中的i(表示您正在访问数组'a'中的每个值 变量“ i”)。这里“ i”不用作索引变量。需要 用'for i in range(0,len(a))'更新它(这意味着迭代 for循环,直到索引值为'i'的数组'a'的长度。
代码:
a = [10, 20, 30, 40, 50, 60]
flag = 0
inp = int(input("Enter digit"))
for i in range(0,len(a)):
if inp == a[i]:
print("You found it")
print("index = ", i)
flag = 1
break
if flag == 0:
print("No found")
输出:
答案 8 :(得分:0)
您可以使用in
在列表中进行检查
lst = [11, 1, 4, 15, 6]
userInput = int(input('Enter Value')) # IF IT IS INT
if userInput in lst:
print(userInput, lst.index(userInput))
答案 9 :(得分:0)
您正面临这个问题,因为在for循环中,我获取了数组值并将其存储在i中,这就是显示索引错误的原因。
在这里找到找到输入号和匹配号的代码:
a=[10,20,30,40,50,60]
inp=20
i=0
for i in a:
c = i
print(c)
if inp==i:
print("You found it")
代码输出:
10
20
You found it
30
40
50
60