在python列表的每个列表中移动特定值(基于该值)

问题描述 投票:1回答:1

我有一个看起来像这样的列表列表:

list= [[0,1,0,0,0][0,0,0,2,0],...,[0,0,10,0,0]]

我想作为输出,是将所有值(1,2 ..,10)移到它们所在列表的开头,所以类似:

list= [[1,0,0,0,0][2,0,0,0,0],...,[10,0,0,0,0]]

我已经尝试过:

new_list= list.insert(0, list.pop(list.index(value)))

适用于一个列表,但我想对列表中的所有列表执行此操作。

python list move listitem
1个回答
0
投票

您可以排序:

l = [[0,1,0,0,0],[0,0,0,2,0],[0,0,10,0,0]]
print([sorted(i, reverse=True) for i in l])

输出:

[[1, 0, 0, 0, 0], [2, 0, 0, 0, 0], [10, 0, 0, 0, 0]]
© www.soinside.com 2019 - 2024. All rights reserved.