[英]In my python program how do I count the number of times a value has occurred
I made some code that prints 100 random values from a range 1-8, and if the number is from 1-5 it prints and x next to it and if it 6-8 it prints a y.我编写了一些代码,打印 1-8 范围内的 100 个随机值,如果数字是 1-5,它会打印并在它旁边打印 x,如果它是 6-8,它会打印一个 y。 I'm wondering how I can print the number of times an x is printed and ay is printed.
我想知道如何打印 x 和 a 的打印次数。
I'm also wondering why i had to make a conditional statement for every individual value i wanted to print x for, instead of just writing this (which didn't work properly)我也想知道为什么我必须为我想打印 x 的每个单独的值做一个条件语句,而不是只写这个(这不能正常工作)
Put x and y in a dictionary and increment every time in the loop, the frequency they occur:将 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
You can create 2 variables to remember how many times x and y is printed.您可以创建 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.