Python列表移动

我正在尝试将列表中的第二个值移动到每个嵌套列表的列表中的第三个值.我尝试了以下,但它没有按预期工作.

List = [['a','b','c','d'],['a','b','c','d'],['a','b','c','d']]
print(List)
col_out = [List.pop(1) for col in List]
col_in = [List.insert(2,List) for col in col_out]
print(List)

结果

[['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd']]
[['a', 'b', 'c', 'd'], [...], [...]]

期望的结果

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

UPDATE

基于pynoobs评论,我想出了以下内容.但我仍然不在那里.为什么’c’打印?

List = [['a','b','c','d'],['a','b','c','d'],['a','b','c','d']]
col_out = [col.pop(1) for col in List for i in col]
print(col_out)

结果

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

最佳答案

[List.insert(2,List) for col in col_out]
               ^^^^ -- See below.

您将整个列表作为元素插入同一列表中.想想递归!

另外,请不要在列表理解中使用状态改变表达式.列表理解不应修改任何变量.礼貌不好!

在你的情况下,你会做:

lists = [['a','b','c','d'],['a','b','c','d'],['a','b','c','d']]
for lst in lists:
    lst[1], lst[2] = lst[2], lst[1]
print(lists)

输出:

[['a', 'c', 'b', 'd'], ['a', 'c', 'b', 'd'], ['a', 'c', 'b', 'd']]
点赞