注意:这不是重复的问题,因为标题可能会说
如果我有一个list列表,则需要从中获取所有组合并进行替换。
import itertools
l = [[1,2,3] ,[1,2,3], [1,2,3]]
n = []
for i in itertools.product(*l):
if sorted(i) not in n:
n.append(sorted(i))
for i in n:
print(i)
[1, 1, 1]
[1, 1, 2]
[1, 1, 3]
[1, 2, 2]
[1, 2, 3]
[1, 3, 3]
[2, 2, 2]
[2, 2, 3]
[2, 3, 3]
[3, 3, 3]
感谢@RoadRunner和@Idlehands。
上面的代码完美,有两个问题:
对于较大的列表,itertools.product引发MemoryError。当l有18个3个长度的子列表时,给出的合并数约为4亿。
订单很重要,因此sorted
无法解决我的问题。这可能会使某些人感到困惑,因此在下面的示例中进行说明。
l = [[1,2,3], [1], [1,2,3]]
在这里,我有2个独特的群组:
组1:元素0、2具有相同的值[1,2,3]
第2组:元素1的值为[1]
因此,我需要的解决方案是:
[1,1,1]
[1,1,2]
[1,1,3]
[2,1,2]
[2,1,3]
[3,1,3]
因此位置1
固定为1
。
希望这个例子有帮助。
编辑答案:
根据新信息,为了处理过多的组合超载itertools.product()
,我们可以尝试小批量提取列表:
from itertools import product
l = [list(range(3))]*18
prods = product(*l)
uniques = set()
results = []
totals = 0
def run_batch(n=1000000):
for i in range(n):
try:
result = next(prods)
except StopIteration:
break
unique = tuple(sorted(result))
if unique not in uniques:
uniques.add(unique)
results.append(result)
global totals
totals += i
run_batch()
print('Total iteration this batch: {0}'.format(totals))
print('Number of unique tuples: {0}'.format(len(uniques)))
print('Number of wanted combos: {0}'.format(len(results)))
输出:
Total iteration this batch: 999999
Number of unique tuples: 103
Number of wanted combos: 103
First 10 results:
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2)
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1)
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2)
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2)
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1)
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2)
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2)
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2)
在这里,我们可以通过调用next(prod)
您选择的范围来控制批量大小,并根据需要继续操作。将uniques
集合中的已排序元组作为参考点,并且将results
它们按所需的正确顺序排列。当我用3 ^ 18的列表运行时,两个大小应该相同,并且令人惊讶地小。我对内存分配不是很熟悉,但是这种方式程序不应该将所有不需要的结果存储在内存中,因此您应该有更多的摆动空间。否则,您始终可以选择将导出results
到文件以腾出空间。显然,此示例仅显示列表的长度,但是您可以根据自己的目的轻松显示/保存该列表。
我不能说这是最好的方法或最优化的方法,但是它似乎对我有用。也许对您有用吗?该批次大约需要10秒钟才能运行5次(平均每批次2秒钟)。整个过程prods
花了我15分钟才能运行:
Total iteration: 387420102
Number of unique tuples: 190
Number of wanted combos: 190
原始答案:
@RoadRunner使用sort()
和提供了一个简洁的解决方案defaultdict
,但我觉得不需要后者。我利用了他的sort()
建议,并在此处实施了修改版本。
从这个答案:
l = [[1] ,[1,2,3], [1,2,3]]
n = []
for i in itertools.product(*l):
if sorted(i) not in n:
n.append(sorted(i))
for i in n:
print(i)
输出:
[1, 1, 1]
[1, 1, 2]
[1, 1, 3]
[1, 2, 2]
[1, 2, 3]
[1, 3, 3]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句