Python python 的集合自动生成,求大神帮忙看看

2unhot · 2019年02月18日 · 最后由 独缺 回复于 2019年02月19日 · 1409 次阅读
# 2个骰子时
dice_list = [
    [one, two]
        for one in range(1,7)
            for two in range(1,7)
]


# 5个骰子时
dice_list = [
    [one, two, three, four, fire]
        for one in range(1,7)
            for two in range(1,7)
                for three in range(1,7)
                    for four in range(1,7)
                        for fire in range(1,7)
]

# 输入骰子个数,就能自动生成dice_list,这个函数要怎么写
# 求大神看看
共收到 6 条回复 时间 点赞

没太懂这个啊。。

黑山老妖 回复

每个骰子的点是 1~6
假设 5 个骰子,使用出现的集合 就是 6 的 5 次方

Python3 ,系统方法 itertools.product

def product(*args, repeat=1):
    # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
    # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
    pools = [tuple(pool) for pool in args] * repeat
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        yield tuple(prod)

print(list(product('123456', repeat =6)))
YueChen 回复

感谢~~~~~~~~~~🙏

YueChen 回复

10repeat 计算机都算不过来了😂

#coding=utf-8
from copy import deepcopy

def handle(countNum):
    if countNum<1:
        return []
    a=[[1],[2],[3],[4],[5],[6]]

    for num in range(1,countNum):
        b=[]
        for one in a:
            for i in range(1,7):
                oneCopy=deepcopy(one)
                oneCopy.append(i)
                b.append(oneCopy)
        a=deepcopy(b)
    return a

print(handle(3))
print(len(handle(3)))    

没理解错,你是要所有骰子的点数的列表,看看这个是你要的不,随便写的,命名不规范。。

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册