如何获取用户inpu选择的列表值和过值的索引

2024-06-07 09:04:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望用户可以输入数字,如果数字匹配的列表值,然后程序返回输入的值和它的索引太。你知道吗

我该怎么做? 我已经写了一些代码,但它不工作。。。。你知道吗

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

它正在提高一个索引器。你知道吗


Tags: 代码用户in程序列表forinputif
3条回答
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")

改变

for i in a:
   if inp == a[i]:
       ...

for i in a:
   if inp == i:
       ...

因为for循环迭代列表中的元素(而不是索引)

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

此外,我将字符串input('Enter digit: ')的返回值更改为一旦目标被看到一次,就返回到循环外的intbreak。你知道吗

请参见this question了解如何在编程练习之外编程此行为的解决方案(TL;DR:a.index(inp))。你知道吗

相关问题 更多 >

    热门问题