【问题标题】:create a list which joins each entry of second list and stores it (python)创建一个列表,该列表连接第二个列表的每个条目并存储它(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 list data-structures


【解决方案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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-18
      • 2020-10-29
      • 2015-08-18
      • 1970-01-01
      相关资源
      最近更新 更多