问题描述
我在尝试实现的算法上遇到麻烦.我有两个列表,想从两个列表中进行特定组合.
I’m having trouble wrapping my head around a algorithm I’m try to implement. I have two lists and want to take particular combinations from the two lists.
这是一个例子.
names = 'a', 'b'
numbers = 1, 2
在这种情况下的输出将是:
the output in this case would be:
[('a', 1), ('b', 2)]
[('b', 1), ('a', 2)]
我的名字可能比数字更多,即len(names) >= len(numbers)
.这是一个具有3个名称和2个数字的示例:
I might have more names than numbers, i.e. len(names) >= len(numbers)
. Here's an example with 3 names and 2 numbers:
names = 'a', 'b', 'c'
numbers = 1, 2
输出:
[('a', 1), ('b', 2)]
[('b', 1), ('a', 2)]
[('a', 1), ('c', 2)]
[('c', 1), ('a', 2)]
[('b', 1), ('c', 2)]
[('c', 1), ('b', 2)]
推荐答案
注意:此答案是针对上面提出的特定问题的.如果您来自Google,只是想寻找一种使用Python获得笛卡尔积的方法,那么您可能正在寻找itertools.product
或简单的列表理解-请参阅其他答案.
Note: This answer is for the specific question asked above. If you are here from Google and just looking for a way to get a Cartesian product in Python, itertools.product
or a simple list comprehension may be what you are looking for - see the other answers.
假设len(list1) >= len(list2)
.然后,您似乎想要的是从list1
中获取所有长度为len(list2)
的排列,并将它们与list2中的项目进行匹配.在python中:
Suppose len(list1) >= len(list2)
. Then what you appear to want is to take all permutations of length len(list2)
from list1
and match them with items from list2. In python:
import itertools
list1=['a','b','c']
list2=[1,2]
[list(zip(x,list2)) for x in itertools.permutations(list1,len(list2))]
返回
[[('a', 1), ('b', 2)], [('a', 1), ('c', 2)], [('b', 1), ('a', 2)], [('b', 1), ('c', 2)], [('c', 1), ('a', 2)], [('c', 1), ('b', 2)]]
这篇关于两个列表之间的排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!