简体   繁体   中英

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?

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

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 .

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:

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]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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