Python:如何在if-else语句中显示所有print语句

时间:2016-08-03 03:51:45

标签: python-3.x

这是实验室问题之一:我尝试创建一个程序,生成0到19之间的N个随机整数列表,并计算严格小于5,10,15和20的元素。我想打印全部'There are {} elements between x and y'语句。

当我运行程序时,它只显示第一个,而不显示其他程序。我该如何纠正?

from random import randint
import sys
while True:
    nb_of_elements = input('How many element do you want to generate? ')
    try:
        nb_of_elements = int(nb_of_elements)
        break
    except ValueError:
        print('Input is not an integer, try again...')

L = [randint(0, 19) for _ in range (nb_of_elements)]
print('The list is :', L)
number = [0] * 4
for i in range (nb_of_elements):
    number[L[i] // 5]+=1
for i in range(4):
    if number[i] < 5:
        print('There are {} elements between 0 and 4'.format (number[i]))
    elif 5<= number[i] < 10:
        print('There are {} elements between 5 and 9'.format(number[i]))
    elif 10<= number[i] < 15:
        print('There are {} elements between 10 and 14'.format(number[i]))
    else:
        print('There are {} elements between 15 and 20'.format(number[i]))

2 个答案:

答案 0 :(得分:0)

你的错误在于你试图计算两次范围内的数字。 首先,你使用整数除法技巧:

for i in range (nb_of_elements):
    number[L[i] // 5]+=1

因此,数字已经包含 0--4,5--9,10-14和15--19(含)范围内元素的数量。

然后,在你的if-elif-elif-else块中,你会看到number的值,它是否适合任何这些范围。但是,number包含计数。平均而言,每个元素的计数大约为nb_of_elements / 5

您不需要if-elif-elif-else块。相反,如您所知,循环遍历range(4),并打印每个元素number[i]。每次都会对应下一个范围(您可能需要一些智能的东西来打印范围。5*i5*i+4可能会这样做。)

有趣的是,您想出了一种智能方法来计算范围(number[L[i]//5] += 1)中的数字,然后在if-elif-else链中回落到标准范围比较。我猜一个人可以超越自己。

答案 1 :(得分:0)

您已经找到了一种计算填充nb_of_elements列表的智能方法。现在您可能需要一种智能的方式来打印它。您可以使用enumerate获取for循环中的当前索引:使用此索引,您可以在X和Y之间创建&#39;变量

counts = [0] * 4
for i in range (nb_of_elements):
    counts[L[i] // 5]+=1

# Loop the counts, and keep track of the index for enumerate
for i,count in enumerate(counts):
     # i * 5 will be [0,5,10,15] and i * 5 + 5 will be [5,10,15,20]
     print('There are {} elements between {} and {}'.format (count, i*5, i*5 + 5))

#The list is : [7, 10, 5]
#There are 0 elements between 0 and 5
#There are 2 elements between 5 and 10
#There are 1 elements between 10 and 15
#There are 0 elements between 15 and 20

在Python中,范围is exclusive,意思是“0到5&#39;之间”。是[0,1,2,3,4]。我也为print函数选择了这个表示法:它现在表示在0到5之间&#39; (独家)而不是0到4之间的&#39; (包括)就像你在代码中使用的一样。这当然可以轻松更改:i*5 + 5&gt; i*5 + 4