简体   繁体   English

将值插入列表列表中的每个第 n 个元素

[英]Inserting value to every nth element in list of lists

I have a list of lists in the following manner:我有以下方式的列表列表:

[[45.0, 58.0, 45.0, 520.0],
 [45.0, 58.0, 754.0, 58.0],
 [302.0, 58.0, 302.0, 520.0],
 [563.0, 58.0, 563.0, 520.0],
 [626.0, 58.0, 626.0, 257.0],
 [754.0, 58.0, 754.0, 321.0],
 [563.0, 159.0, 754.0, 159.0],
 [626.0, 257.0, 754.0, 257.0],
 [45.0, 260.0, 110.0, 260.0],
 [302.0, 260.0, 563.0, 260.0],
 [629.0, 321.0, 629.0, 520.0],
 [45.0, 520.0, 629.0, 520.0],
 [110.0, 58.0, 110.0, 322.0],
 [45.0, 129.0, 110.0, 129.0],
 [45.0, 322.0, 302.0, 322.0],
 [563.0, 321.0, 754.0, 321.0],
 [299.0, 520.0, 299.0, 581.0],
 [299.0, 581.0, 562.0, 581.0],
 [562.0, 520.0, 562.0, 581.0],
 [563.0, 450.0, 629.0, 450.0]]

Is there a way I could add for example the element 2 to every second index inside the lists?有没有办法可以将元素2添加到列表中的每个第二个索引?

So the result would look like:所以结果看起来像:

[[45.0, 58.0, 2, 45.0, 520.0, 2],
 [45.0, 58.0, 2, 754.0, 58.0, 2],
 [302.0, 58.0, 2, 302.0, 520.0, 2],
 [563.0, 58.0, 2, 563.0, 520.0, 2],
.
.
.
.

Here is one solution for your issue, using python list properties这是您的问题的一种解决方案,使用 python 列表属性

def insert_in_position(_list, element, position):
    for i in range(len(_list)):
        _list[i] = _list[i][:position]+[element]+_list[i][position:]
    return _list

You may use insert() , append() , andList Comprehension .您可以使用insert()append()List Comprehension

your_list = [[45.0, 58.0, 45.0, 520.0],
    [45.0, 58.0, 754.0, 58.0],
    ...
    [562.0, 520.0, 562.0, 581.0],
    [563.0, 450.0, 629.0, 450.0]]

new_list = [x.insert(2, 2) or x.append(2) or x for x in your_list]

print(new_list)

# result:
[[45.0, 58.0, 2, 45.0, 520.0, 2],
[45.0, 58.0, 2, 754.0, 58.0, 2],
...
[562.0, 520.0, 2, 562.0, 581.0, 2],
[563.0, 450.0, 2, 629.0, 450.0, 2]]

You may also check this Helpful Link : Appending item to lists within a list comprehension .您也可以查看此有用链接将项目附加到列表理解中的列表

More pythonic way:更多pythonic方式:

data = [[45.0, 58.0, 45.0, 520.0],
    [45.0, 58.0, 754.0, 58.0],
    ...
    [562.0, 520.0, 562.0, 581.0],
    [563.0, 450.0, 629.0, 450.0]]

#Directly appending an element to item will impact original dataset, 
#Since list is reference data structure,

for item in data:
    item.append(2) 
print(data)

[[45.0, 58.0, 2, 45.0, 520.0, 2],
[45.0, 58.0, 2, 754.0, 58.0, 2],
...
[562.0, 520.0, 2, 562.0, 581.0, 2],
[563.0, 450.0, 2, 629.0, 450.0, 2]]

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

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