簡體   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