创建一个列表,该列表连接第二个列表的每个条目并存储它(python)

Posted

技术标签:

【中文标题】创建一个列表,该列表连接第二个列表的每个条目并存储它(python)【英文标题】:create a list which joins each entry of second list and stores it (python) 【发布时间】:2017-11-28 14:21:14 【问题描述】:

创建列表列表的最佳方法是什么,该列表的第一个列表的每个值都对应于第二个列表? 喜欢:

a=[1,2,3]
b=[5,6,7]

创建 c 使得:

c=[[1,5][1,6][1,7][2,5][2,6][2,7][3,5][3,6][3,7]]

【问题讨论】:

Python merging two lists with all possible permutations的可能重复 【参考方案1】:

最好的方法是使用itertools 库。

import itertools
a=[1,2,3]
b=[5,6,7]
c=list(itertools.product(a,b))  

但它会生成一个元组列表。如果你特别需要一个列表列表,你可以这样做

c=[[x, y] for x in a for y in b]

【讨论】:

【参考方案2】:
from itertools import product

a = [1, 2, 3]
b = [5, 6, 7]
c = [list(i) for i in product(a, b)]

c的值:

  [[1, 5], [1, 6], [1, 7], [2, 5], [2, 6], [2, 7], [3, 5], [3, 6], [3, 7]]

itertools.product - 来自文档:

初始化签名:itertools.product(self, /, *args, **kwargs) 文档字符串: product(*iterables, repeat=1) --> 产品对象

输入迭代的笛卡尔积。相当于嵌套的 for 循环。

例如,product(A, B) 返回相同的结果: ((x,y) for x in A for y 在 B)。最左边的迭代器在最外面的 for 循环中,所以 输出元组以类似于里程表的方式循环(使用 最右边的元素在每次迭代中都会发生变化)。

要计算可迭代对象与自身的乘积,请指定数字 带有可选的重复关键字参数的重复次数。例如, product(A, repeat=4) 和 product(A, A, A, A) 意思一样。

product('ab', range(3)) --> ('a',0) ('a',1) ('a',2) ('b',0) ('b', 1) ('b',2) 产品((0,1), (0,1), (0,1)) --> (0,0,0) (0,0,1) (0,1,0 ) (0,1,1) (1,0,0) ...

类型:类型

此解决方案使用list comprehension

【讨论】:

以上是关于创建一个列表,该列表连接第二个列表的每个条目并存储它(python)的主要内容,如果未能解决你的问题,请参考以下文章

如何防止 Jquery 可排序连接列表中的重复条目?

JQuery 测验应用程序 - 突出显示无序列表条目和调用函数

python实践中的总结——列表

根据第二个文件中相应的ID列表从文件中提取第一个条目?

性能将列表列表解压缩到pandas数据帧中

复杂项目导入器(列表中的列表),在第二个列表中使用滚动行为苦苦挣扎