[英]Is there a Python function that finds all k-length orderings of a list?
I don't believe this precise question has been asked before.我不相信以前有人问过这个确切的问题。 I was recently faced with a problem where I had to find just such a set.
我最近遇到了一个问题,我必须找到这样一个集合。 An example would probably help:-
一个例子可能会有所帮助:-
Given some list:给出一些列表:
list1 = ['a', 'b']
Is there a function that returns the following set?是否有返回以下集合的函数?
output = {('a', 'b'), ('a', 'a'), ('b', 'b'), ('b', 'a')}
I have been able to generate the desired output using the itertools
combinations_with_replacement
and permutations
functions, as follows:我已经能够产生使用所期望的输出
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')}
Is there a name for such a set?有这样一套的名字吗? Is there an alternative method I can use?
有没有我可以使用的替代方法?
You want itertools.product
:你想要
itertools.product
:
>>> import itertools
>>> set(itertools.product(list1, repeat=2))
{('a', 'b'), ('b', 'a'), ('b', 'b'), ('a', 'a')}
itertools.product
with the repeat
parameter is essentially " permutations_with_replacement
", which seems to be what you want.带有
repeat
参数的itertools.product
本质上是“ permutations_with_replacement
”,这似乎是您想要的。
Itertools.product() does what you want: 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.