所以我已经写了一段代码,它生成一个随机列表,其中包含随机数个值。然后询问用户正在寻找的数字,如果它在列表中,它将告诉用户该数字在列表中的位置。
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()
我想添加一些东西,它将跳过它第一次找到的索引,然后查找复制的索引(如果有)。
当前结果
[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
期望的结果
[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
https://stackoverflow.com/questions/50650250
复制相似问题