Python 两个列表之间的组合?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12935194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:13:14  来源:igfitidea点击:

combinations between two lists?

pythonalgorithmlistcombinations

提问by user1735075

It's been a while and I'm having trouble wrapping my head around a algorithm I'm try to make. Basically, I have two lists and want to get all the combinations of the two lists.

已经有一段时间了,我无法围绕我正在尝试制定的算法进行思考。基本上,我有两个列表,并希望获得两个列表的所有组合。

I might not be explaining it correct so here's a example.

我可能没有正确解释它,所以这里有一个例子。

name = 'a', 'b'
number = 1, 2

the output in this case would be:

在这种情况下,输出将是:

1.  A1 B2
2.  B1 A2

The tricky part is I might have more items in the “name” variable than items in the “number” variable(number will always be equal to or less than the name variable).

棘手的部分是“name”变量中的项目可能比“number”变量中的项目多(数字始终等于或小于 name 变量)。

I'm confused how to do all the combinations (nested for loop?) and even more confused on the logic to shift the items in the name variable in the event that there are more items in name than they are in the number list.

我对如何进行所有组合(嵌套 for 循环?)感到困惑,甚至对在 name 中的项目多于数字列表中的项目时移动 name 变量中的项目的逻辑更加困惑。

I'm not the best programmer but think I can give it a shot if someone can help me clarify the logic/algoriythm to achieve this. So I have just been stuck on nested for loops.

我不是最好的程序员,但我认为如果有人可以帮助我澄清实现这一目标的逻辑/算法,我可以试一试。所以我一直被困在嵌套的 for 循环中。

Update:

更新:

Here's the output with 3 variables and 2 numbers:

这是带有 3 个变量和 2 个数字的输出:

name = 'a', 'b', 'c'
number = 1, 2

output:

输出:

1.  A1 B2
2.  B1 A2
3.  A1 C2
4.  C1 A2
5.  B1 C2
6.  C1 B2

采纳答案by interjay

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.productor a simple list comprehension may be what you are looking for - see the other answers.

注意:这个答案是针对上面提出的特定问题。如果您从 Google 来到这里,并且只是在寻找一种在 Python 中获得笛卡尔积的方法,itertools.product或者您可能正在寻找一个简单的列表理解 - 请参阅其他答案。



Suppose len(list1) >= len(list2). Then what you appear to want is to take all permutations of length len(list2)from list1and match them with items from list2. In python:

假设len(list1) >= len(list2)。然后,你似乎需要的是采取长的所有排列len(list2)list1,并与列表2项匹配。在蟒蛇中:

import itertools
list1=['a','b','c']
list2=[1,2]

[list(zip(x,list2)) for x in itertools.permutations(list1,len(list2))]

Returns

退货

[[('a', 1), ('b', 2)], [('a', 1), ('c', 2)], [('b', 1), ('a', 2)], [('b', 1), ('c', 2)], [('c', 1), ('a', 2)], [('c', 1), ('b', 2)]]

回答by Mass Zhou

a tiny improvement for the answer from interjay, to make the result as a flatten list.

对来自 interjay 的答案进行了微小的改进,使结果成为展平的列表。

>>> list3 = [zip(x,list2) for x in itertools.permutations(list1,len(list2))]
>>> import itertools
>>> chain = itertools.chain(*list3)
>>> list4 = list(chain)
[('a', 1), ('b', 2), ('a', 1), ('c', 2), ('b', 1), ('a', 2), ('b', 1), ('c', 2), ('c', 1), ('a', 2), ('c', 1), ('b', 2)]

reference from this link

来自此链接的参考

回答by DrIDK

The simplest way is to use itertools.product:

最简单的方法是使用itertools.product

a = ["foo", "melon"]
b = [True, False]
c = list(itertools.product(a, b))
>> [("foo", True), ("foo", False), ("melon", True), ("melon", False)]

回答by user3684792

Without itertools

没有迭代工具

[(list1[i], list2[j]) for i in xrange(len(list1)) for j in xrange(len(list2))]

回答by logic

May be simpler than the simplest one above:

可能比上面最简单的更简单:

>>> a = ["foo", "bar"]
>>> b = [1, 2, 3]
>>> [(x,y) for x in a for y in b]  # for a list
[('foo', 1), ('foo', 2), ('foo', 3), ('bar', 1), ('bar', 2), ('bar', 3)]
>>> ((x,y) for x in a for y in b)  # for a generator if you worry about memory or time complexity.
<generator object <genexpr> at 0x1048de850>

without any import

没有任何进口

回答by ThorSummoner

I was looking for a list multiplied by itself with only unique combinations, which is provided as this function.

我一直在寻找一个仅具有唯一组合的自乘列表,该列表作为此函数提供。

import itertools
itertools.combinations(list, n_times)


Here as an excerpt from the Python docs on itertoolsThat might help you find what your looking for.

此处作为That上 Python 文档 itertools的摘录可能会帮助您找到您要查找的内容。

Combinatoric generators:

Iterator                                 | Results
-----------------------------------------+----------------------------------------
product(p, q, ... [repeat=1])            | cartesian product, equivalent to a 
                                         |   nested for-loop
-----------------------------------------+----------------------------------------
permutations(p[, r])                     | r-length tuples, all possible 
                                         |   orderings, no repeated elements
-----------------------------------------+----------------------------------------
combinations(p, r)                       | r-length tuples, in sorted order, no 
                                         |   repeated elements
-----------------------------------------+----------------------------------------
combinations_with_replacement(p, r)      | r-length tuples, in sorted order, 
                                         | with repeated elements
-----------------------------------------+----------------------------------------
product('ABCD', repeat=2)                | AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD
permutations('ABCD', 2)                  | AB AC AD BA BC BD CA CB CD DA DB DC
combinations('ABCD', 2)                  | AB AC AD BC BD CD
combinations_with_replacement('ABCD', 2) | AA AB AC AD BB BC BD CC CD DD

回答by Idanmel

You might want to try a one line list comprehension:

您可能想尝试单行列表理解:

>>> [name+number for name in 'ab' for number in '12']
['a1', 'a2', 'b1', 'b2']
>>> [name+number for name in 'abc' for number in '12']
['a1', 'a2', 'b1', 'b2', 'c1', 'c2']

回答by computerist

Answering the question "given two lists, find all possible permutations of pairs of one item from each list" and using basic Python functionality (i.e., without itertools) and, hence, making it easy to replicate for other programming languages:

回答问题“给定两个列表,从每个列表中找到一个项目对的所有可能排列”并使用基本的 Python 功能(即,没有 itertools),因此,很容易复制到其他编程语言:

def rec(a, b, ll, size):
    ret = []
    for i,e in enumerate(a):
        for j,f in enumerate(b):
            l = [e+f]
            new_l = rec(a[i+1:], b[:j]+b[j+1:], ll, size)
            if not new_l:
                ret.append(l)
            for k in new_l:
                l_k = l + k
                ret.append(l_k)
                if len(l_k) == size:
                    ll.append(l_k)
    return ret

a = ['a','b','c']
b = ['1','2']
ll = []
rec(a,b,ll, min(len(a),len(b)))
print(ll)

Returns

退货

[['a1', 'b2'], ['a1', 'c2'], ['a2', 'b1'], ['a2', 'c1'], ['b1', 'c2'], ['b2', 'c1']]

回答by Ishan Rastogi

the best way to find out all the combinations for large number of lists is:

找出大量列表的所有组合的最佳方法是:

import itertools
from pprint import pprint

inputdata = [
    ['a', 'b', 'c'],
    ['d'],
    ['e', 'f'],
]
result = list(itertools.product(*inputdata))
pprint(result)

the result will be:

结果将是:

[('a', 'd', 'e'),
 ('a', 'd', 'f'),
 ('b', 'd', 'e'),
 ('b', 'd', 'f'),
 ('c', 'd', 'e'),
 ('c', 'd', 'f')]

回答by Fletch F Fletch

Or the KISS answer for short lists:

或短名单的 KISS 答案:

[(i, j) for i in list1 for j in list2]

Not as performant as itertools but you're using python so performance is already not your top concern...

性能不如 itertools,但您使用的是 python,因此性能已经不是您最关心的问题...

I like all the other answers too!

我也喜欢所有其他答案!