[英]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
.我想重新排序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.您需要访问a_list
每个子列表,然后在该子列表中重新排序。 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
.首先,您需要为a_list
的子列表找到解决方案。 So you'll be able to map that solution to a_list
elements.因此,您将能够将该解决方案映射到a_list
元素。
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祝你好运
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.