栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python:枚举列表中所有元素的可能组合

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python:枚举列表中所有元素的可能组合

Python:枚举列表中所有元素的可能组合
  • 问题描述
  • 解决方案

问题描述

前言:比如有5个不同的产品,分别为a, b, c, d, e,需要列出所有可能的组合,因为每种产品存在“有”和“没有”2种可能,所以总共就有2的5次方,也就是32种可能;

如何用Python进行枚举呢?

解决方案
from itertools import combinations

def combine(temp_list, n):
    '''根据n获得列表中的所有可能组合(n个元素为一组)'''
    temp_list2 = []
    for c in combinations(temp_list, n):
        temp_list2.append(c)
    return temp_list2

list1 = ['a', 'b', 'c', 'd', 'e']
end_list = []
for i in range(len(list1)+1):
    end_list.extend(combine(list1, i))
    
print(end_list)
print(len(end_list))

[(), (‘a’,), (‘b’,), (‘c’,), (‘d’,), (‘e’,), (‘a’, ‘b’), (‘a’, ‘c’),
(‘a’, ‘d’), (‘a’, ‘e’), (‘b’, ‘c’), (‘b’, ‘d’), (‘b’, ‘e’), (‘c’,
‘d’), (‘c’, ‘e’), (‘d’, ‘e’), (‘a’, ‘b’, ‘c’), (‘a’, ‘b’, ‘d’), (‘a’,
‘b’, ‘e’), (‘a’, ‘c’, ‘d’), (‘a’, ‘c’, ‘e’), (‘a’, ‘d’, ‘e’), (‘b’,
‘c’, ‘d’), (‘b’, ‘c’, ‘e’), (‘b’, ‘d’, ‘e’), (‘c’, ‘d’, ‘e’), (‘a’,
‘b’, ‘c’, ‘d’), (‘a’, ‘b’, ‘c’, ‘e’), (‘a’, ‘b’, ‘d’, ‘e’), (‘a’, ‘c’,
‘d’, ‘e’), (‘b’, ‘c’, ‘d’, ‘e’), (‘a’, ‘b’, ‘c’, ‘d’, ‘e’)]
32

原文链接:link


加油!

感谢!

努力!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/349713.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号