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

Time:10-21

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

CodePudding user response:

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; i.e., 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']]

CodePudding user response:

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]

CodePudding user response:

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

  • Related