繁体   English   中英

在列表中重新排序列表值的正确方法是什么?

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

我想重新排序a_list列表的值。

这是我目前的片段:

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)

这是我当前的输出:

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

这是我想要的输出:

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

您需要访问a_list每个子列表,然后在该子列表中重新排序。 使用列表理解,它会是这样的:

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

您当前的代码对子列表本身重新排序; 即,例如,如果你开始

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

那么结果就是

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

首先,您需要为a_list的子列表找到解决方案。 因此,您将能够将该解决方案映射到a_list元素。

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

然后您可以安全地将此函数映射(理解)到列表列表。

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

我建议这个,

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)

这可能不是最合适的解决方案,
但我认为你可以这样做。
谢谢
祝你好运

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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