【问题标题】:Python automatically extract list index in and append dataPython自动提取列表索引并附加数据
【发布时间】:2018-08-23 14:52:06
【问题描述】:

我不知道如何描述这个问题。举个例子:

a=[[1,2],[3,4],[5,6]]
b=[['a','b'],['c','c']]
x=[a,b]

现在我想将x 元素的元素附加到它们之前的元素中(在这种情况下,b 的元素在每个 a 的元素上),我可以使用它

t=[]
for i in a:
    for j in b:
        t.append(i+j)

然后我想要的结果变成了:

t
[[1, 2, 'a', 'b'],
 [1, 2, 'c', 'c'],
 [3, 4, 'a', 'b'],
 [3, 4, 'c', 'c'],
 [5, 6, 'a', 'b'],
 [5, 6, 'c', 'c']]

在这种情况下,我知道 x 中有 ab,所以我可以附加它们。但是,如果我不知道 x 中有多少项,我该如何追加元素?

点赞x=[a,b,c,d,e,...]

尝试过使用循环,但似乎不太好。我在想combination,但不知道该怎么做。

【问题讨论】:

    标签: python list loops append combinations


    【解决方案1】:

    使用itertools'productchain 函数(分别)生成成对乘积并将它们展平:

    from itertools import chain, product    
    t = [list(chain.from_iterable(i)) for i in product(a, b)]
    

    print(t)
    [[1, 2, 'a', 'b'],
     [1, 2, 'c', 'c'],
     [3, 4, 'a', 'b'],
     [3, 4, 'c', 'c'],
     [5, 6, 'a', 'b'],
     [5, 6, 'c', 'c']]
    

    此解决方案将推广到任意数量的列表:

    x = [a, b, c, ...]
    t = [list(chain.from_iterable(i)) for i in product(*x)]
    

    【讨论】:

    • 你的解决方案还是需要我知道a和b,如果x中也有c、d、.e怎么办?
    • @Zhonghao.KevinXie product(*x),其中x = [a, b, c, ...]
    • 谢谢,如果允许,我会批准你的回答。
    猜你喜欢
    • 2015-08-03
    • 2015-11-29
    • 2018-05-24
    • 2020-08-13
    • 2022-01-10
    • 1970-01-01
    • 2018-12-14
    • 2021-03-28
    • 2021-04-16
    相关资源
    最近更新 更多