两个长度不等的列表之间的排列 [英] Permutations between two lists of unequal length

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

问题描述

我在尝试实现的算法上遇到麻烦.我有两个列表,想从两个列表中进行特定组合.

这是一个例子.

 名称= ['a','b']数字= [1,2] 

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

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

我的名字可能比数字更多,即 len(names)> = len(numbers).这是一个具有3个名称和2个数字的示例:

 名称= ['a','b','c']数字= [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 或简单的列表理解-请参见其他答案.


假设 len(list1)> = len(list2).然后,您似乎想要的是从 list1 中获取长度为 len(list2)的所有排列,并将它们与list2中的项目进行匹配.在python中:

 导入itertoolslist1 = ['a','b','c']list2 = [1,2][itertools.permutations(list1,len(list2))中x的list(zip(x,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)]] 

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.

Here’s an example.

names = ['a', 'b']
numbers = [1, 2]

the output in this case would be:

[('a', 1), ('b', 2)]
[('b', 1), ('a', 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]

output:

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

解决方案

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.


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

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

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

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