Home > Software design >  How to process every nth element in each of this list of lists?
How to process every nth element in each of this list of lists?

Time:12-25

I have a list of lists that looks like this;

list_of_lists = 
[
 [1640, 4, 0.173, 0.171, 0.172, 472], 
 [1640, 5, 0.173, 0.171, 0.173, 259], 
 [1640, 6, 0.175, 0.173, 0.173, 180], 
]

I want to process the 2nd element of every list inside this list of lists such that it is replaced by 2 elements created by adding 1 to it. It will look like this;

new_list_of_lists = 
[
 [1640, 5, 5, 0.173, 0.171, 0.172, 472], 
 [1640, 6, 6, 0.173, 0.171, 0.173, 259], 
 [1640, 7, 7, 0.175, 0.173, 0.173, 180], 
]

How can this be done using python 3.9? Thank you.

CodePudding user response:

You could use a list comprehension:

list_of_lists = 
[
 [1640, 4, 0.173, 0.171, 0.172, 472], 
 [1640, 5, 0.173, 0.171, 0.173, 259], 
 [1640, 6, 0.175, 0.173, 0.173, 180], 
]

output = [[x[0], x[1]   1, x[1]   1, x[2], x[3], x[4], x[5]] for x in list_of_lists]
print(output)

This prints:

[
    [1640, 5, 5, 0.173, 0.171, 0.172, 472],
    [1640, 6, 6, 0.173, 0.171, 0.173, 259],
    [1640, 7, 7, 0.175, 0.173, 0.173, 180]
]

CodePudding user response:

I Would suggest using a list "slice" to replace the 2nd element (slice [1:2]) with a 2-element list:

for list in list_of_lists:
    list[1:2] = [list[1]   1] * 2

CodePudding user response:

first method: update each element individually

list_of_lists[0][1]  = 1
list_of_lists[1][1]  = 1
list_of_lists[2][1]  = 1

second method: update all element

for num in range(len(list_of_lists)):
list_of_lists[num][1]  = 1

CodePudding user response:

You can use a list comprehension and a variable to tell it which index should be processed:

list_of_lists = [
 [1640, 4, 0.173, 0.171, 0.172, 472], 
 [1640, 5, 0.173, 0.171, 0.173, 259], 
 [1640, 6, 0.175, 0.173, 0.173, 180], 
]

i = 1
new_list_of_lists = [a[:i] [a[i] 1]*2 a[i 1:] for a in list_of_lists]

print(new_list_of_lists)
[[1640, 5, 5, 0.173, 0.171, 0.172, 472], 
 [1640, 6, 6, 0.173, 0.171, 0.173, 259], 
 [1640, 7, 7, 0.175, 0.173, 0.173, 180]]
  • Related