首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从用户输入检查列表中的重复项

从用户输入检查列表中的重复项
EN

Stack Overflow用户
提问于 2018-06-02 03:56:07
回答 4查看 456关注 0票数 2

所以我已经写了一段代码,它生成一个随机列表,其中包含随机数个值。然后询问用户正在寻找的数字,如果它在列表中,它将告诉用户该数字在列表中的位置。

代码语言:javascript
运行
复制
import random

a = [random.randint(1, 20) for i in range(random.randint(8, 30))]

a.sort()
print(a)


def askUser():

    n = input("What number are you looking for?")
    while not n.isdigit():
        n = input("What number are you looking for?")

    n = int(n)
    s = 0

    for numbers in a:
        if numbers == n:
            s += 1
            print("Number", n, "is located in the list and the position is:", (a.index(n)+1))
            # Something here to skip this index next time it goes through the loop
        else:
            pass
    if s == 0:
        print("Your number could not be found")


askUser()

我想添加一些东西,它将跳过它第一次找到的索引,然后查找复制的索引(如果有)。

当前结果

代码语言:javascript
运行
复制
[2, 4, 8, 9, 10, 10, 16, 19, 20, 20]
What number are you looking for?20
Number 20 is located in the list and the position is: 9
Number 20 is located in the list and the position is: 9

期望的结果

代码语言:javascript
运行
复制
[2, 4, 8, 9, 10, 10, 16, 19, 20, 20]
What number are you looking for?20
Number 20 is located in the list and the position is: 9
Number 20 is located in the list and the position is: 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50650250

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档