两个列表之间的组合? [英] combinations between two lists?

查看:124
本文介绍了两个列表之间的组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这已经有一段时间,我有麻烦环绕我的头周围的算法,我尽量让。基本上,我有两个列表,并希望得到这两个列表的所有组合。

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

 名称='A','B'
数= 1,2
 

在此情况下,输出将是:

  1。 A1 B2
2. B1 A2
 

最棘手的部分是我可以有更多的项目在名称变比数字变项(数量将始终等于或小于名义变量)。

我很困惑该怎么办所有组合(嵌套的循环?),甚至在逻辑,有其名更多的项目比他们的数量转移事件的名义变量的项目越糊涂列表中。

我不是最好的程序员,但觉得我可以给它一个镜头,如果有人能帮助我澄清逻辑/ algoriythm实现这一目标。所以,我刚才一直停留在嵌套的循环。

更新:

下面是3个变量和2个数字输出:

 名称='A','B','C'
数= 1,2
 

输出:

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

解决方案

假设 LEN(List1中)> = LEN(list2中)。然后,你似乎有什么想是采取长的所有排列 len个(list2中)的List1 ,并与项目匹配它们从list2中。在蟒蛇:

 >>>进口itertools
>>>的List1 = ['一','B','C']
>>> list2中= [1,2]
>>> [拉链(X,list2中)对于x在和itertools.permutations(List1中,LEN(list2中))]
[[('一个',1),('B',2)],[('一个',1),(c位,2)],[('B',1),('一个' ,2)],[('B',1),(c位,2)],[('C',1),('一个',2)],[('C',1), ('B',2)]]
 

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).

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.

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.

Update:

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

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

解决方案

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]
>>> [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)]]

这篇关于两个列表之间的组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆