[英]how to insert a column to a list of lists in python
I have the following list (which is much larger in reality) 我有以下列表(实际上更大)
[(1, 2, 3),
(1, 2, 3),
(1, 2, 3)]
and would like to insert 2 columns to it so it results in 并想在其中插入2列,这样
[(c1, 1, c2, 2, 3),
(c1, 1, c2, 2, 3),
(c1, 1, c2, 2, 3)]
the best which I came up with is the following 我想出的最好的是以下
mylist = [(1, 2, 3),(1, 2, 3),(1, 2, 3)]
mylist_new = []
for i in mylist:
mylist_new.append(('c1', i[0], 'c2', i[1], i[2], i[3]))
any alternative suggestions on how to achieve this? 关于如何实现这一目标的任何其他建议?
You could use list comprehension. 您可以使用列表推导。
mylist = [(1, 2, 3),(1, 2, 3),(1, 2, 3)]
mylist_new = [('c1', i, 'c2', j, k) for (i, j, k) in mylist]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.