python - 将项目插入列表中的列表

标签 python list python-3.x

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

例如:我想将 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)

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

最佳答案

只需zip x与每个列表a,b,c使用列表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 正在做的事情。

关于python - 将项目插入列表中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39428982/

相关文章:

python - Python 中 Podio 文件上传失败

python - 用Python发送邮件主题

Python:枚举的切片

python - 使用 pymysql 在 MySql 中插入空日期

python - 通过放置一个列表中的第 n 个项目和另一个列表中的其他项目来合并 Python 中的列表?

python - geojsonio 中的 display() 给出 401 错误

python-3.x - 查找两个长度不等的字符串之间的差异

python - 如何使用Python中的函数连续扩展列表?

python - 按第二个值对嵌套列表进行排序

python - 如何将文本文件的多行作为字典中键的值(在元组中)?