我是一名蟒蛇初学者。我想从一个列表中获取两个组合列表。
例如,我有一个列表:
c = [1, 2, 3, 4]
我想使用每四个项目来填充两个列表。会有((2^4)/2)-1
种可能性。
c1 = [1] c2 = [2, 3, 4]
c1 = [2] c2 = [1, 3, 4]
c1 = [3] c2 = [2, 3, 4]
c1 = [4] c2 = [1, 2, 3]
c1 = [1, 2] c2 = [3, 4]
c1 = [1, 3] c2 = [2, 4]
c1 = [1, 4] c2 = [2, 3]
此功能通常适用于此类任务itertools
,但我无法选择itertools.combination
生成的列表数。
该功能只允许我选择每个列表应该有多少项。
例如,如果我尝试跟随功能,
print list(itertools.combinations(c, 2))
我只能得到这样的结果。
[(1,2),(1,3),(1,4),(2,3),(2,4),(3,4)]
我很难找到这个,但我找不到任何东西。
更新
哦,我可怜的英语造成了这样的混乱!我完全改变了我的榜样。我想将4个项目分配到2个列表。抱歉混乱!
答案 0 :(得分:3)
我不确定您对 10选择2 的理解是什么。您从list(itertools.combinations(c, 2))
收到的输出在数学上定义为 10C2 。
从编辑到您的问题,您似乎想要一种完全不同的组合。结果的数量仍然不是45,而是: 10C1 + 10C2 + 10C3 + 10C4 + 10C5 。
我希望以下内容可以帮助您前进:
for i in range(1, 6):
for c1 in itertools.combinations(c, i):
c1 = set(c1)
c2 = set(c) - c1
print c1, c2
以上代码的灵感来自于this (deleted) answer CSZ {/ 3}}。
使用range(1, 3)
时收到的输出:
[1] [2, 3, 4, 5, 6, 7, 8, 9, 10]
[2] [1, 3, 4, 5, 6, 7, 8, 9, 10]
[3] [1, 2, 4, 5, 6, 7, 8, 9, 10]
[4] [1, 2, 3, 5, 6, 7, 8, 9, 10]
[5] [1, 2, 3, 4, 6, 7, 8, 9, 10]
[6] [1, 2, 3, 4, 5, 7, 8, 9, 10]
[7] [1, 2, 3, 4, 5, 6, 8, 9, 10]
[8] [1, 2, 3, 4, 5, 6, 7, 9, 10]
[9] [1, 2, 3, 4, 5, 6, 7, 8, 10]
[10] [1, 2, 3, 4, 5, 6, 7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 9, 10]
[9, 5] [1, 2, 3, 4, 6, 7, 8, 10]
[10, 5] [1, 2, 3, 4, 6, 7, 8, 9]
[6, 7] [1, 2, 3, 4, 5, 8, 9, 10]
[8, 6] [1, 2, 3, 4, 5, 7, 9, 10]
[9, 6] [1, 2, 3, 4, 5, 7, 8, 10]
[10, 6] [1, 2, 3, 4, 5, 7, 8, 9]
[8, 7] [1, 2, 3, 4, 5, 6, 9, 10]
[9, 7] [1, 2, 3, 4, 5, 6, 8, 10]
[10, 7] [1, 2, 3, 4, 5, 6, 8, 9]
[8, 9] [1, 2, 3, 4, 5, 6, 7, 10]
[8, 10] [1, 2, 3, 4, 5, 6, 7, 9]
[9, 10] [1, 2, 3, 4, 5, 6, 7, 8]
答案 1 :(得分:2)
<!DOCTYPE html>
<html ng-app>
<head>
<link rel="stylesheet" href="style.css">
<!--<link rel="stylesheet" href="bootstrap.css">-->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="bootstrap.css">
<!-- Latest compiled and minified JavaScript -->
<script src="angular.min.js"></script>
<script src="cordova.js"></script>
<script src="angular.animate.min.js"></script>
<script src="angular.route.min.js"></script>
<link rel="stylesheet" href="font-awesome.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
</body>
<script type="text/javascript" src="pro.js"></script>
<script type="text/javascript" src="bootstrap.js"></script>
<script type="text/javascript" src="script.js"></script>
</html>
如果你想要所有的组合。你可以这样做。
l = [1,2,3,4, 5, 6, 7, 8]
print [[l[:i], l[i:]] for i in range(1, len(l))]
或
print [l[i:i+n] for i in range(len(l)) for n in range(1, len(l)-i+1)]