简体   繁体   English

随机化 itertools.combinations

[英]Randomising itertools.combinations

I have a list, l1 , which I have generated all combinations of length 2 using itertools.combinations.我有一个列表l1 ,我使用 itertools.combinations 生成了长度为 2 的所有组合。 I intend to loop through these combinations, and perform an operation on them.我打算遍历这些组合,并对它们执行操作。 For simplicity, this code simply prints combination a .为简单起见,此代码仅打印组合a

import itertools

l1 = [1,2,3,4,5]
for a in itertools.combinations(l1,2):
    print(a)

Is there any way to randomise the order that the combinations are looped through?有没有办法随机化组合循环的顺序? random.shuffle does not appear to work, as itertools.combinations has no length. random.shuffle似乎不起作用,因为 itertools.combinations 没有长度。

Why not save the combinations as a variable and then shuffle?:为什么不将组合保存为变量然后随机播放?:

import itertools
import random

l1 = [1,2,3,4,5]
combs = list(itertools.combinations(l1,2))
random.shuffle(combs)
for a in combs:
    print(a)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM