python多列表间的排列组合

学习来源:https://blog.csdn.net/wuuud1/article/details/83991951
涉及的函数库讲解:https://www.runoob.com/python/python-func-reduce.html

涉及使用的库:python3:from functools import reduce

# 常见写法
def lists_combination(lists, code=''):
    '''输入多个列表组成的列表, 输出其中每个列表所有元素可能的所有排列组合
    code用于分隔每个元素'''
    try:
        import reduce
    except:
        from functools import reduce
        
    def myfunc(list1, list2):
        return [str(i)+code+str(j) for i in list1 for j in list2]
    return reduce(myfunc, lists)

# 高手的写法
fn = lambda x, code=',': reduce(lambda x, y: [str(i)+code+str(j) for i in x for j in y], x)
# 调用时直接写:fn(lists, code)

案例:

from functools import reduce
a = [['A', 'B'], ['C', 'D', 'E'],['F','G','H']]

# 常见写法
def lists_combination(lists, code=''):
    '''输入多个列表组成的列表, 输出其中每个列表所有元素可能的所有排列组合
    code用于分隔每个元素'''
    def myfunc(list1, list2):
        return [str(i) + code + str(j) for i in list1 for j in list2]

    return reduce(myfunc, lists)

print('常见写法的结果:\n', lists_combination(a, '+'))  # 排列结果用+号连接

# 高手写法
fn = lambda x, code='|': reduce(lambda x, y: [str(i)+code+str(j) for i in x for j in y], x)
# 直接调用fn(lists, code)
res = fn(a, '+')
print('高手写法的结果:\n', res)

执行的结果:
在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值