python列出所有的组合列表

1:说下项目的需求,有一个游戏角色,这个角色有多个组成部位,如头,脚,手,眼睛等等,每一个部位都有对应的几张图片,求一个游戏角色所有有可能的组合,由于我这里是需要生成每一对应组合的全部游戏角色对应的图片,所以必须要知道每一个游戏角色组合里的对应的每一个部件的图片路径,所以有了下面的解决办法

2:要是确定了游戏角色能拆成多少个部件的话,解决思路是很简单的,就是使用多个for循环,就能列出所有的组合,有多少个部件,就有多少个for循环,这个有点类似数学里的阶乘,这里就不贴出代码了

3:要是不确定游戏角色能拆成多少个部件时,那么我们就不确定使用多少个for循环列表了,而且如果有十个部件,那么就有十个for循环,经常使用for循环的都知道,for嵌套一般都是很少超过3个的,在放弃for循环后,我想到了递归的解决方案,这里贴出相应的代码,有类似需求的,可以参考大概的实现

def get_path_list(indexlist, pathlist, onepathlist, partindex, countlist):

    index = indexlist[partindex]
    onepathlist.append("part{0}/{1}.png".format(partindex+1, index))

    if partindex + 1 >= len(countlist):
        pathlist.append(onepathlist)
        onepathlist = []
        partindex = 0

        rev_indexlist = indexlist.copy()
        rev_indexlist.reverse()
        for i, n in enumerate(rev_indexlist):
            index_part = len(countlist) - i - 1
            if i+1 >= len(countlist):
                break
            else:
                # 不等于最后一个时
                if n + 1 >= countlist[index_part]: #最后一层满了,上一层加1
                    if indexlist[index_part-1] + 1 >= countlist[index_part-1]:
                        continue
                    else:
                        indexlist[index_part-1] += 1
                        # index_part-1后面的层置为0
                        for j in range(len(countlist) - index_part):
                            indexlist[index_part+j] = 0
                        return get_path_list(indexlist, pathlist, onepathlist, partindex, countlist)
                else:
                    indexlist[index_part] += 1
                    return get_path_list(indexlist, pathlist, onepathlist, partindex, countlist)

        return pathlist
    else:
        partindex = partindex + 1
        return get_path_list(indexlist, pathlist, onepathlist, partindex, countlist)

if __name__ == '__main__':

    indexlist = [0, 0, 0] #当前的部件序列表,需要与countlist的长度一致
    countlist = [2, 2, 2] #当前的每个部件所对应的个数
    pathlist = [] #包含的全部部件的所有组合
    onepathlist = [] #一个组合里的部件文件
    partindex = 0 #当前准备添加的第几个部件

    pathlist = get_path_list(indexlist, pathlist, onepathlist, partindex, countlist)

    for path in pathlist:
        print(path)
# 输出
# ['part1/0.png', 'part2/0.png', 'part3/0.png']
# ['part1/0.png', 'part2/0.png', 'part3/1.png']
# ['part1/0.png', 'part2/1.png', 'part3/0.png']
# ['part1/0.png', 'part2/1.png', 'part3/1.png']
# ['part1/1.png', 'part2/0.png', 'part3/0.png']
# ['part1/1.png', 'part2/0.png', 'part3/1.png']
# ['part1/1.png', 'part2/1.png', 'part3/0.png']
# ['part1/1.png', 'part2/1.png', 'part3/1.png']

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值