简体   繁体   English

是否有一个 Python 函数可以找到列表的所有 k 长度排序?

[英]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_replacementpermutations功能,如下所示:

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.

相关问题 将K长度列表拆分为尽可能“均匀”的L子列表,即使K / L留下余数 - Splitting a K-length list into L sub-lists that are as “even” as possible, even if K/L leaves a remainder 递归算法,用于在Python中生成列表长度k的所有排列 - Recursive Algorithm to generate all permutations of length k of a list in Python 用所有可能的顺序创建N个最大长度为K的列表 - create N lists of maximum lengt K with all possible orderings Python-从索引k开始查找列表A中最小元素的索引 - Python - Finds the index of the smallest element in the list A from index k onwards python长度为0.1的所有可能的组合 - python all possible combinations of 0,1 of length k 创建一个接受两个整数参数的 python 函数,找到它们之间的所有素数并在列表中返回这些素数 - Create a python function that accepts two integer parameters, finds all prime numbers between them and return these primes in a list python中字符串的所有可能的长度k组合 - all possible length k combinations of a string in python 如何获取列表的所有排序,使列表等于另一个列表? - How to get all orderings of a list such that the list is equal to another list? 在 Python 中查找字符串的所有字典顺序的替代方法 - Alternate way to find all lexicographic orderings of a string in Python Python 正则表达式在列表中仅找到一项不是全部 - Python regex finds only one item in list not all
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM