如何基于python生成list的所有的子集
作者:Alan_LJP 时间:2021-09-24 07:31:31
这篇文章主要介绍了如何基于python生成list的所有的子集,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
不使用递归且不引入标准库,单纯用两个for循环即可得出一个list的所有子集
L = [1, 2, 3, 4]
List = [[]]
for i in range(len(L)): # 定长
for j in range(len(List)): # 变长
sub_List = List[j] + [L[i]]
if sub_List not in L:
List.append(sub_List)
print('List =', List)
主要思想:
变长的 List 中的所有元素将会被不断地重复遍历,直到遍历完定长的 L
当然,不进行条件判断也行:
L = [1, 2, 3, 1]
List = [[]]
for i in range(len(L)): # 定长
for j in range(len(List)): # 变长
List.append(List[j] + [L[i]])
print('List =', List)
最后,如果考虑到程序的效率问题,那么建议引入 python 标准库中的 itertools,然后调用 combinations 这个函数
这样可以更加高效地得到一个 list 的所有的子集
代码如下:
from itertools import combinations
L = [1, 2, 3, 1]
result_list = sum([list(map(list, combinations(L, i))) for i in range(len(L) + 1)], [])
print('result_list =', result_list)
来源:https://www.cnblogs.com/Alan-LJP/p/11831228.html
标签:python,生成,list,子集
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python numpy 模块介绍
2022-06-04 02:03:00
uni-app网络请求、数据缓存实例详解
2023-08-09 03:49:12
WinHTTP Services 5.1 参考资料
2010-03-27 20:49:00
如何在windows下安装Pycham2020软件(方法步骤详解)
2023-05-19 14:07:30
![](https://img.aspxhome.com/file/2023/0/89300_0s.png)
pycharm安装包失败的解决方法
2022-03-29 04:24:04
![](https://img.aspxhome.com/file/2023/1/97281_0s.png)
asp如何准确获知对方来访问的时间和URL?
2010-07-07 12:25:00
用Python画一个LinkinPark的logo代码实例
2022-09-27 05:52:19
![](https://img.aspxhome.com/file/2023/9/90339_0s.png)
pandas实现数据可视化的示例代码
2023-01-12 10:31:05
![](https://img.aspxhome.com/file/2023/5/97725_0s.png)
一文详解Python中多进程和进程池的使用方法
2023-12-01 04:10:12
php官方微信接口大全(微信支付、微信红包、微信摇一摇、微信小店)
2023-10-17 14:16:56
go swagger生成接口文档使用教程
2023-10-20 12:31:35
![](https://img.aspxhome.com/file/2023/7/100797_0s.png)
python深度学习tensorflow训练好的模型进行图像分类
2023-02-20 20:40:37
![](https://img.aspxhome.com/file/2023/7/76087_0s.jpg)
一种弹出提示信息时页面背景色调改变的方法
2008-12-01 12:22:00
python读写LMDB文件的方法
2021-12-17 15:12:37
![](https://img.aspxhome.com/file/2023/3/98833_0s.jpg)
Python 识别12306图片验证码物品的实现示例
2021-04-03 22:17:24
![](https://img.aspxhome.com/file/2023/0/92340_0s.png)
Sql Server “因为文件组primary已满,未能为数据库XX对象XX分配空间”问题的解决
2010-05-16 21:27:00
SQL优化基础 使用索引(一个小例子)
2012-01-29 18:29:26
使用numba对Python运算加速的方法
2022-05-12 20:30:57
PHP加密函数 Javascript/Js 解密函数
2023-06-15 18:03:03
详解python requests中的post请求的参数问题
2023-09-20 07:50:40
![](https://img.aspxhome.com/file/2023/0/95410_0s.png)