创建随机数列表.询问用户并检查数字是否在所需范围内


list = []
import random
for i in range(20):
list.append(random.randrange(1,9))
print("List = ", list)
number = int(input("Tell me a number between 1 and 9: "))
if number > 0 and number < 10 and number in list:
print("The number",number,"is in the desired range", list.count(number), "times")
for number in list:
print("Indexes of", number, "=", list.index(number))

##########################
# I can´t solve this last part correctly

您可以使用enumerate来获取列表中项目的索引和值,并检查值是否为数字,然后打印索引

from random import randrange
numbers = [randrange(1, 9) for _ in range(20)]
print("numbers = ", numbers)
number = int(input("Tell me a number between 1 and 9: "))
if 0 < number < 10 and number in numbers:
print("The number", number, "is in the desired range", numbers.count(number), "times")
for index, val in enumerate(numbers):
if val == number:
print("Indexes of", number, "=", index)

numbers =  [3, 6, 3, 3, 5, 8, 3, 2, 4, 4, 3, 5, 7, 6, 2, 1, 2, 4, 6, 8]
Tell me a number between 1 and 9: 4
The number 4 is in the desired range 3 times
Indexes of 4 = 8
Indexes of 4 = 9
Indexes of 4 = 17

看来你在找索引。此外,请使用f-strings,并正确命名变量。也就是说,您可以使用

import random
# initialisation
lst = [random.randrange(1, 9) for _ in range(20)]
print("List = ", lst)
# input
number = int(input("Tell me a number between 1 and 9: "))
if number in lst and (0 < number < 10):
print(f"The number {number} is in the desired range {lst.count(number)} times")
indices = [index for index, value in enumerate(lst) if value == number]
print(f"The indices are {indices}")

最好不要像list那样使用built-in function作为变量,索引总是返回第一索引,您需要enumerate如下:(我尽量不改进OP的代码)

lst = []
import random
for i in range(20):
lst.append(random.randrange(1,9))
print("List = ", lst)
number = int(input("Tell me a number between 1 and 9: "))
if number > 0 and number < 10 and number in lst:
print("The number",number,"is in the desired range", lst.count(number), "times")
idxs = [idx  for idx , num in enumerate(lst) if num==number]
print("Indexes of", number, "=", idxs)

输出:

List =  [4, 6, 5, 6, 6, 3, 5, 7, 5, 4, 6, 3, 4, 7, 1, 5, 2, 1, 2, 6]
Tell me a number between 1 and 9: 3
The number 3 is in the desired range 2 times
Indexes of 3 = [5, 11]

你可以试试这个方法:

(因为所有的随机数在(1,10)范围内,如果输入的数字在这个范围内的数字存在于列表中,你不需要number in lst)

import random
lst = [random.choice(range(1,10)) for _ in range(20)]
print("List = ", lst)
number = int(input("Tell me a number between 1 and 9: "))
if number in range(1,10):
print("The number",number,"is in the desired range", lst.count(number), "times")
idxs = [idx  for idx , num in enumerate(lst) if num==number]
print("Indexes of", number, "=", idxs)

相关内容

  • 没有找到相关文章