如何在Python中调用随机列表函数而不更改它?

How to call the random list function without chaning it in Python?

我真的需要帮助。我定义了一个函数,它给出了 n 面骰子的 x 掷骰数。现在我被要求计算每一面的频率,考虑到可能有更多的面(不仅仅是 6 个)而我所做的是 freq1 += 1 似乎不起作用;

我定义的第一个函数是dice(x),

freq_list = list(range(1,(n+1)))
rollfreq = [0]*n
for w in dice(x):
    rollfreq[w-1] += 1

print zip(freq_list,rollfreq)

我得到一个列表,如 [(1,0),(2,4),(3,1)...] 等等,这是预期的,但问题是 rollfreq 值与原始随机生成的 dice(x) 列表不匹配。我认为这是因为它是 RNG,它也更改了第二个 运行 中 dice(x) 的值,因此我无法引用我最初随机生成的 dice(x) 函数。有什么解决办法吗?我的意思是我几乎尝试了所有方法,但它显然不起作用!

编辑:

import random

n = raw_input('Number of the sides of the dice: ')
n = int(n)
x = raw_input('Number of the rolls: ')
x = int(x)

def dice():
    rolls = []
    for i in range(x):
        rolls.append(random.randrange(1, (n+1)))
    return rolls
print dice()
freq_list = list(range(1,(n+1)))
rollfreq = [0]*n
for w in dice():
        rollfreq[w-1] += 1

print 'The number of frequency of each side:', zip(freq_list,rollfreq)

我已经添加了代码-希望你们能帮我解决这个问题,谢谢!

您调用了 dice() 函数两次,一次是在打印它时,一次是在 for 循环中迭代它时。不同的结果来自那里。

import random

n = raw_input('Number of the sides of the dice: ')
n = int(n)
x = raw_input('Number of the rolls: ')
x = int(x)

def dice():
    rolls = []
    for i in range(x):
        rolls.append(random.randrange(1, (n+1)))
    return rolls

freq_list = list(range(1,(n+1)))
rollfreq = [0]*n

# Grab the rolls
rolls = dice()
# Print them here
print(rolls)

for w in rolls:
        rollfreq[w-1] += 1

print 'The number of frequency of each side:', zip(freq_list,rollfreq)