在我的python程序中,我如何计算值发生的次数

时间:2016-04-10 00:01:27

标签: python-3.x

我的代码:

 my code

我制作了一些代码,可以打印1-8范围内的100个随机值,如果数字是1-5,则打印,x旁边是x,如果是6-8则打印y。我想知道如何打印x打印的次数和y的打印次数。

我也想知道为什么我必须为我想要打印x的每个单独的值制作一个条件语句,而不是只写这个(它没有正常工作)

如果num == 1或2或3或4或5:

好吧,谢谢堆(我真的生锈了)

2 个答案:

答案 0 :(得分:1)

将x和y放入字典中并在循环中每次递增,它们发生的频率:

import random

numbers = {'x': 0, 'y': 0}


def randomnumbers():
    for x in range(100):
        n = random.randint(1, 8)

        if 1 <= n <= 5:
            numbers['x'] += 1
            print('%dx' % n)
            # E.g. 1x
        elif 6 <= n <= 8:
            numbers['y'] += 1
            print('%dy' % n)
            # E.g. 7y


randomnumbers()
print('x %d times' % numbers['x'])
# E.g. x 61 times
print('y %d times' % numbers['y'])
# E.g. y 39 times

答案 1 :(得分:0)

您可以创建2个变量来记住x和y的打印次数。

import random

howManyX = 0 # how many times x is printed
howManyY = 0 # how many times y is printed

def randomnumbers():
    for i in range(100):
       num = random.randint(1, 8)

       # if your number is from range 1 - 5: print x and increment howManyX
       if 1 <= num <= 5:
           print(num, 'x')
           howManyX += 1
       # if your variable is not from range 1 - 5 (in this case it is 6, 7 or 8): print y and increment howManyY
       else:
           print(num, 'y')
           howManyY += 1  

randomnumbers()
#now you can print how many times have x and y occurred
print(howManyX, howManyY)