Python中重复次数有限的组合 [英] Combinations with limited repeats in Python

查看:95
本文介绍了Python中重复次数有限的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何使用itertools在Python中获得列表的所有组合,但是如果我想限制重复次数怎么办?

I know how to get ALL combinations of a list in Python with itertools, but what if I want to limit the amount of repeats?

所以,如果我有[1、2、3、4、5]

So, if I have [1, 2, 3, 4, 5]

但是我想将每个项目的组合限制为仅3次重复(最终列表的长度固定为10):

But I want to limit combinations to only 3 repeats of each item (with a fixed length of the final list, say 10):

[1, 1, 1, 2, 3, 3, 5, 5, 5, 4]
[1, 2, 3, 3, 3, 4, 5, 5, 4, 4]
[4, 4, 1, 1, 1, 5, 2, 2, 2, 3]

,依此类推.我该怎么做?

and so on. How do I do this?

推荐答案

这将起作用:

import random

L = [1, 2, 3, 4, 5]
L3 = L * 3
random.shuffle(L3)
L3[:10]

这篇关于Python中重复次数有限的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆