【发布时间】:2018-06-01 19:56:06
【问题描述】:
所以我编写了一个代码,它生成一个随机值的随机列表。然后询问用户用户正在寻找什么号码,如果它在列表中,它会告诉用户该号码在列表中的哪个位置。
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
【问题讨论】:
-
a = random.choices(range(1, 20), k = random.randint(8, 30))可能比您的列表组合更好。
标签: python python-3.x list input