【问题标题】:Insert items to lists within a list将项目插入列表中的列表
【发布时间】:2016-09-10 17:56:27
【问题描述】:

我想创建一个包含多个列表的列表,特别考虑一个列表。

例如:我想将abc 中的项目添加到x 列表中,然后将x 附加到一个主列表中。

mainlist = []
x = [1, 2, 3] # items will be added hear.

a = ['a1', 'b1', 'c1']
b = ['a2', 'b2', 'c2']
c = ['a3', 'b3', 'c3']

首先我需要为x 创建一个列表列表:

x = [[i] for i in x]

返回:

out[1]: [[1], [2], [3]]

现在,我想将项目添加到这些列表中:

for item in range(0, len(x)):
    x[item].insert(1, a[item])

out[2]: [[1, 'a1'], [2, 'b1'], [3, 'c1']]

然后追加到mainlist:

mainlist.append(x)
out[3]: [[[1, 'a1'], [2, 'b1'], [3, 'c1']]]

我的问题是如何像使用 a 列表一样从 bc 添加项目,以获得此输出:

[[[1, 'a1'], [2, 'b1'], [3, 'c1']], [1, 'a2'], [2, 'b2'], [3, 'c2']], [1, 'a3'], [2, 'b3'], [3, 'c3']]]

我试过了,我得到了结果,但是我认为这段代码可以改进。

item1 = [[i] for i in x]
item2 = [[i] for i in x]
item3 = [[i] for i in x]

for i in range(0, len(item1)):
    item1[i].insert(1, a[i])

for i in range(0, len(item2)):
    item2[i].insert(1, b[i])

for i in range(0, len(item3)):
    item3[i].insert(1, c[i])

mainlist.append(item1)
mainlist.append(item2)
mainlist.append(item3)

任何改进它的建议都值得赞赏。谢谢!

【问题讨论】:

    标签: python list python-3.x


    【解决方案1】:

    只需 zip x 与每个列表 a,b,c 使用 list comp:

    x = [1, 2, 3] # items will be added hear.
    
    a = ['a1', 'b1', 'c1']
    b = ['a2', 'b2', 'c2']
    c = ['a3', 'b3', 'c3']
    
    main_list = [zip(x, y) for y in a,b,c]
    

    这会给你:

    [[(1, 'a1'), (2, 'b1'), (3, 'c1')], [(1, 'a2'), (2, 'b2'), (3, 'c2')], [(1, 'a3'), (2, 'b3'), (3, 'c3')]]
    

    如果你真的想要子列表而不是元组,你可以调用 map 将元组映射到列表:

     [list(map(list, zip(x, y))) for y in a,b,c]
    

    如果您要使用没有 zip 逻辑的常规循环,您可以执行以下操作:

    l = []
    for y in a, b, c: 
        l.append([[x[i], ele] for i, ele in enumerate(y)])
    print(l)
    

    或相同的列表组合版本:

     [[[x[i], ele] for i, ele in enumerate(y) ] for y in a, b, c]
    

    假设所有的长度都与x 相同,每个iy 中当前元素的索引,我们将其与x 中的相应元素匹配,这也正是zip 正在做的.

    【讨论】:

    • 谢谢,@Padraic。很好的解决方案。谢谢你的解释。
    • 不用担心,与 zip 的区别在于它会截断到最短列表的长度,枚举会给出一个 IndecError。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-18
    • 1970-01-01
    • 1970-01-01
    • 2011-12-22
    • 1970-01-01
    相关资源
    最近更新 更多