在编写这段代码时,我发现自己做了很多重复的事情,并且想知道是否有更简单,更简单或更短的方法来完成这样的重复性任务。
以下是相关代码:
from random import randint
RandomNumber = Zeroes = Ones = Twos = Threes = Fours = Fives = Sixes = i = 0
while i < 1000000:
RandomNumber = (randint(0,6))
if RandomNumber == 0:
Zeroes = Zeroes + 1
if RandomNumber == 1:
Ones = Ones + 1
if RandomNumber == 2:
Twos = Twos + 1
if RandomNumber == 3:
Threes = Threes + 1
if RandomNumber == 4:
Fours = Fours + 1
if RandomNumber == 5:
Fives = Fives + 1
if RandomNumber == 6:
Sixes = Sixes + 1
i = i + 1
答案 0 :(得分:2)
你去......
string.Empty
答案 1 :(得分:2)
不是为每个随机输出获取命名变量,而是可以将每个可能值作为键的字典。这将缩短您的代码并使其可扩展到任何随机范围
float x= 15;
void *y;
y = &x;
printf("\tValue of X is : %f \n", x);
printf("\tValue of y is : %d", (int)*(float *)y);
示例输出:
from random import randint
randomMax = 6
randomList= {i:0 for i in range(0,randomMax+1)}
totalIterations = 10000
while totalIterations >0:
randomList[randint(0,randomMax)]+=1
totalIterations-=1
答案 2 :(得分:1)
首先,当你发现自己使用大量适合相同目的的变量时(例如零,一,二等数),你几乎肯定需要一个数组(Python术语中的list
)。
import random
nums = [0] * 7 # number of digits from zero to six
for i in range(1000001):
r = random.randint(0, 6) # you can get rid of this variable
# and use random.randint(0, 6) as an array index
nums[r] += 1 # each member of a list represents a number of some digit's occurrences
print(''.join("{} -> {}\n".format(a, b) for a, b in zip(range(7), nums)))
如果你想要一些非常简短,快速和强大的东西:
import random, collections
print(''.join("{} -> {}\n".format(a, b) for a, b in collections.Counter(random.randint(0, 6) for _ in range(100)).items()))
选中this,了解如何使用collections.Counter
计算列表项的出现次数。
这段代码很快,并且在使用生成器时不会浪费内存。
答案 3 :(得分:1)
此代码可能有所帮助,计数器字典将数字作为键,数字出现为值。
from random import randint
counter = {}
while i < 1000000:
RandomNumber = (randint(0,6))
if RandomNumber in counter:
counter[RandomNumber] += 1
else:
counter[RandomNumber] = 1
i += 1
答案 4 :(得分:1)
>>> from random import randint
>>> randomnumber = [0,0,0,0,0,0,0]
>>> i = 0
>>> while i < 100:
... random = (randint(0,6))
... randomnumber[random] +=1
... i = i +1
...
>>> randomnumber
[18, 15, 10, 8, 16, 19, 14]
答案 5 :(得分:0)
在您的特殊情况下,您可以
from random import randint
results=[0]*7 # same as [0,0,0,0,0,0,0]
i=0
while i < 1000000:
n = randint(0,6)
results[n]+=1
i+=1
for i in range(len(results)):
print(i, results[i])
答案 6 :(得分:0)
这些答案都可行,但是他们将花费很长时间非常循环,而实际上你根本不需要使用循环。这里的代码占用了一段时间,而不是需要循环超过一百万次:
from random import random
nums = [random() for _ in range(7)]
nums = [int((x / sum(nums)) * 1000000) for x in nums]
不可否认,这种方法总共有点1000000,但它的更多,更多更快,你也可以添加一些随机的,使它实际上是1000000。
有关详细信息,请参阅:
Getting N random numbers that the sum is M
Random numbers that add to 100: Matlab(有关此生成的统计分布的信息)