简体   繁体   中英

What is a proper way to re-order the values of a list inside a list?

I would like to re-order the values of the lists inside a_list .

This is my current snippet:

a_list = [["a", "b", "c"], ["a", "b", "c"], ["a", "b", "c"]]
order = [1, 0, 2]

a_list = [a_list[i] for i in order] 

print(a_list)

This is my current output:

[['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]

This is my desired output:

[['b', 'a', 'c'], ['b', 'a', 'c'], ['b', 'a', 'c']]

You need to access each sublist of a_list , and then reorder within that sublist. Using list comprehension, it would be like:

a_list = [["a", "b", "c"], ["a", "b", "c"], ["a", "b", "c"]]
order = [1, 0, 2]

a_list = [[sublst[i] for i in order] for sublst in a_list]

print(a_list) # [['b', 'a', 'c'], ['b', 'a', 'c'], ['b', 'a', 'c']]

Your current code reorders the sublists themselves; ie, for example, if you started with

a_list = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]

then the result would have been

[['d', 'e', 'f'], ['a', 'b', 'c'], ['g', 'h', 'i']]

First you need to find a solution for a sublist in a_list . So you'll be able to map that solution to a_list elements.

def reorder(xs, order):
    # I am omitting exceptions etc. 
    return [xs[n] for n in order]

Then you can safely map (comprehend) this function to list of lists.

[reorder(xs, order) for xs in a_list]

I suggest this,

import copy

a_list = [["a", "b", "c"], ["a", "b", "c"], ["a", "b", "c"]]
order = [1, 0, 2]

lis = copy.deepcopy(a_list)

ind = 0
for i in range(len(a_list)):
    ind = 0
    for j in order:
        lis[i][ind] = a_list[i][j]
        ind += 1

a_list = lis

print(a_list)

This maybe not the most appropriate solution,
But I think you can do it like this.
Thank you
Best of luck

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