尝试为任意数量的掷骰生成一个包含所有值的 python 列表。为什么每个值都附加到返回列表中的多个索引?

Trying to generate a python list of all values for any number of die rolls. Why is each value appended to multiple indexes in the returned list?

这是我尝试创建的函数,它可以生成 x 次掷骰的每个结果。 main函数中生成的第一个列表是[[1],[2],[3],[4],[5],[6]],replicated list是这个数字顺序重复6次的列表.将 1 加到第一个六分之一,将 2 加到第二个六分之一,依此类推将得到一个列表,其中包含滚动 2(或更多)骰子的每个结果。

#Works for any number of sides on a dice
#Meant to expand the list to include an extra dice. The items needed for 1 
#dice is 6, for 2 die is 36, etc.
def replicate(x,y):
    new_lst = []
    for i in range(y):
        for k in x:
            new_lst.append(k)
    return new_lst

#Specifically for 6 sided die
def table_of_possibilities(x):
    or_lst = []
    for l in range(6):
        or_lst.append([l + 1])
    if x > 1:
        for k in range(x-1):
            lst = replicate(or_lst,6)
            length = len(lst)
            print(lst)
            #This list appears fine, lists of [1],[2],[3],[4],[5],[6] repeated 6 times
            for i in range(length):
                if i < length / 6:
                    lst[i].append(1)
                elif i < length / 3:
                    lst[i].append(2)
                elif i < length / 2:
                    lst[i].append(3)
                elif i < length * 2 / 3:
                    lst[i].append(4)
                elif i < length * 5 / 6:
                    lst[i].append(5)
                else:
                    lst[i].append(6)
    return lst

print(table_of_possibilities(2))
#The final list is the earlier print with 1,2,3,4,5,6 in each list

如果您可以在列表中处理元组,那么也许 itertools.product 就足够了:

from itertools import product

myList = list(product(range(1,7), repeat=2)) # the second argument can be however
                                            # many die you want to roll.
print myList

在python 2.7(我正在使用的)中,这个returns:

[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 1), (2 , 2), (2, 3), (2, 4), (2, 5), (2, 6), (3, 1), (3, 2), (3, 3), (3, 4 ), (3, 5), (3, 6), (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (4, 6), (5, 1), (5, 2), (5, 3), (5, 4), (5, 5), (5, 6), (6, 1), (6, 2), (6 , 3), (6, 4), (6, 5), (6, 6)]

可在此处找到更多信息: 9.7 itertools