[英]Splitting a K-length list into L sub-lists that are as “even” as possible, even if K/L leaves a remainder
[英]Is there a Python function that finds all k-length orderings of a list?
我不相信以前有人問過這個確切的問題。 我最近遇到了一個問題,我必須找到這樣一個集合。 一個例子可能會有所幫助:-
給出一些列表:
list1 = ['a', 'b']
是否有返回以下集合的函數?
output = {('a', 'b'), ('a', 'a'), ('b', 'b'), ('b', 'a')}
我已經能夠產生使用所期望的輸出itertools
combinations_with_replacement
和permutations
功能,如下所示:
from itertools import combinations_with_replacement, permutations
set1 = set(combinations_with_replacement(['a', 'b'], 2))
set2 = set(permutations(['a', 'b'], 2))
>>> set1
{('a', 'b'), ('a', 'a'), ('b', 'b')}
>>> set2
{('b', 'a'), ('a', 'b')}
set1.update(set2)
>>> set1
{('a', 'b'), ('a', 'a'), ('b', 'b'), ('b', 'a')}
有這樣一套的名字嗎? 有沒有我可以使用的替代方法?
你想要itertools.product
:
>>> import itertools
>>> set(itertools.product(list1, repeat=2))
{('a', 'b'), ('b', 'a'), ('b', 'b'), ('a', 'a')}
帶有repeat
參數的itertools.product
本質上是“ permutations_with_replacement
”,這似乎是您想要的。
Itertools.product() 做你想要的:
mylist = ['a', 'b']
list(itertools.product(mylist, repeat=2))
Out[8]: [('a', 'a'), ('a', 'b'), ('b', 'a'), ('b', 'b')]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.