简体   繁体   中英

How to process every nth element in each of this list of lists?

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.

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

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

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

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

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