我正在尝试学习Python,并且在分配时遇到了一些麻烦。
问题是:在我们的随机列表中出现了多少次出现的数字9?
我需要弄清楚如何正确地将它添加为while和if语句的函数。
random_list = []
list_length = 20
number = 0
while number < list_length:
random_list.append(random.randint(0,10))
number += 1
print random_list
print count
提前谢谢
答案 0 :(得分:0)
根据此分配的规则,您可以使用以下内容。更改位于while循环的中间,您检查随机生成的int
的值。如果它等于9,则添加到计数中。
random_list = []
list_length = 20
count = 0
number = 0
while number < list_length:
#Generate a random number and assign it to randInt
randInt = random.randint(0,10)
#Append the number you just generated to the list
random_list.append(randInt)
number += 1
def countNines(list):
count = 0
#If the number is 9, add to the count
for num in list:
if num == 9:
count += 1
return count
count = countNines(random_list)
print random_list
print count