You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何正确重排列嵌套列表内各子列表的内部元素?

你当前的列表推导式是对a_list的外层子列表做重排序,而你的三个子列表内容完全一致,所以运行后看不出变化,无法实现子列表内部元素重排的需求。

你需要遍历每个子列表,再按照order定义的索引顺序重新拼接子列表的元素,修改后的代码如下:

a_list = [["a", "b", "c"], ["a", "b", "c"], ["a", "b", "c"]]
order = [1, 0, 2]

a_list = [[sublist[i] for i in order] for sublist in a_list]

print(a_list)

运行后输出即为你期望的结果:

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

如果你不想生成新的列表,需要原地修改原有列表,可以用循环实现:

a_list = [["a", "b", "c"], ["a", "b", "c"], ["a", "b", "c"]]
order = [1, 0, 2]

for sub in a_list:
    sub[:] = [sub[i] for i in order]

print(a_list)

内容的提问来源于stack exchange,提问作者Andalusia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 05:15:01