我有一个像这样的数组:
a = [[ 8, 7, 6, 5, 9],
[1, 2, 1, 6, 4],
[4, 2, 5, 4, 2]]`
我想根据第二行更改该数组的顺序,如下所示:b = [2, 6, 1, 1, 4]
所以,我希望结果变成这样:
a = [[7, 5, 8, 6, 9],
[2, 6, 1, 1, 4],
[2, 4, 4, 5, 2]]
如何在Python中解决此问题?
a = [[ 8, 7, 6, 5, 9],
[1, 2, 1, 6, 4],
[4, 2, 5, 4, 2]]
a[1] = [2, 6, 1, 1, 4]
尝试一下。
在此答案中,我做出以下两个假设:
如果以上两个假设都成立,则可以使用list comprehension on a nested list,并创建一个列表以指定应如何对列表进行重新排序。
a = [[8, 7, 6, 5, 9],
[1, 2, 1, 6, 4],
[4, 2, 5, 4, 2]]
new_ord = [1, 3, 0, 2, 4]
b = [[l[i] for i in new_ord] for l in a]
print(b) #prints: [[7, 5, 8, 6, 9], [2, 6, 1, 1, 4], [2, 4, 4, 5, 2]]