使用itertools库在python中从30个元素中选择11个元素时,如何解决内存错误?

时间:2019-06-24 14:01:22

标签: python permutation itertools

我有两支球队的板球运动员名单。

假设总共有30位玩家,我想从这30位玩家中随机选择11位。我希望所有组合都存储在列表中。

我尝试使用python中的itertools.permutations。但是我得到了MemoryError。有什么办法可以解决此问题或我可以使用的Python中的其他任何库?

from itertools import permutations   
name=["p1","p2","p3","p4","p5","p6","p7","p8","p9","p10","p11","p12","p13","p14","p15","p16","p17","p18","p19","p20","p21","p22","p23","p24","p25","p26","p27","p28","p29","p30"]  
combinations = list(permutations(name,11))

这是我得到的错误:

Traceback (most recent call last):  
  File "PythonDemo.py", line 3, in <module>  
    combinations = list(permutations(name,11))  
MemoryError

2 个答案:

答案 0 :(得分:1)

可以用30!/(30 - 11)!的方式选择30个元素中的11个,大约是2e+16。因此,您想要的列表将占用数EB的内存!

由于所有排列都是预先计算的,我建议使用random.choices

import random

name = ["p1","p2","p3","p4","p5","p6","p7","p8","p9","p10","p11","p12","p13","p14","p15","p16","p17","p18","p19","p20","p21","p22","p23","p24","p25","p26","p27","p28","p29","p30"]

for i in range(3):
    combination = random.choices(name, k=11)
    print(combination)

请注意,random.choices仅在Python 3.6和更高版本中可用。

继续使用itertools.permutations

您还可以坚持使用itertools.permutations,例如像这样保持发电机运行:

from itertools import permutations

name = ["p1","p2","p3","p4","p5","p6","p7","p8","p9","p10","p11","p12","p13","p14","p15","p16","p17","p18","p19","p20","p21","p22","p23","p24","p25","p26","p27","p28","p29","p30"]  
combinations = permutations(name, 11)

for i in range(3):
    combination = next(combinations)
    print(combination)

请注意,这不会随机选择一个组合,而是会产生非常可预测的组合。这可能是好事,也可能是坏事,具体取决于您的用例。

答案 1 :(得分:0)

尝试使用由排列生成的迭代器,而不要使用它重新创建列表。

import itertools

name = [f'p{a}' for a in range(1, 31)]
combinations = itertools.permutations(name, 11)

for item in combinations:
   do_the_stuff(item)