简体   繁体   English

从列表中插入列表中的元素

[英]Insert element in list of list from list

Want to insert list elements in list of list such that first element of list should be inserted to first index of first list of list then second element of list of list to first element of 2nd list of list and so on... For eg.想要在列表列表中插入列表元素,以便列表的第一个元素应插入到列表的第一个列表的第一个索引,然后将列表的第二个元素插入到列表的第二个列表的第一个元素,依此类推......例如。

lst_of_lst = [[1,2,3,4][5,6,7,8][9,10,11,12][13,14,15,16]]
list = ['a','b','c','d']

output - lst_of_lst=[['a',1,2,3,4]['b',5,6,7,8]['c',9,10,11,12]['d',13,14,15,16]]

All you need to do is just iterate over your the list you want to insert the items from and just insert the respective item at 0th position.您需要做的只是遍历您要从中插入项目的列表,然后在第 0 个 position 处插入相应的项目。

It can be done as follows:可以按如下方式完成:

for i in range(len(list)):
    lst_of_lst[i].insert(0, list[i])

That's it!而已!

Also, you missed , in defining lst_of_lst, it will give you error.另外,你错过了,在定义 lst_of_lst 时,它会给你错误。 And also it is not a good way to name any variable or data structure a name of data type.而且,将任何变量或数据结构命名为数据类型的名称也不是一个好方法。 Like you did for list array.就像你对列表数组所做的那样。 You can change it to _list if you want.如果需要,您可以将其更改为 _list。

Little trickery for fun/speed:乐趣/速度的小把戏:

lst_of_lst = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
list = ['a','b','c','d']

for L, L[:0] in zip(lst_of_lst, zip(list)):
    pass

print(lst_of_lst)

Try it online! 在线尝试!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM