简体   繁体   English

Python列表移动

[英]Python List Column Move

I'm trying to move the second value in a list to the third value in a list for each nested list. 我正在尝试将列表中的第二个值移动到每个嵌套列表的列表中的第三个值。 I tried the below, but it's not working as expected. 我尝试了以下,但它没有按预期工作。

Code

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)

Result 结果

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

Desired Result 期望的结果

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

UPDATE UPDATE

Based upon pynoobs comment, i came up with the following. 基于pynoobs评论,我想出了以下内容。 But i'm still not there. 但我仍然不在那里。 Why is 'c' printing? 为什么'c'打印?

Code

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)

Result 结果

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

You are inserting an entire list as an element within the same list. 您将整个列表作为元素插入同一列表中。 Think recursion! 想想递归!


Also, please refrain from using state-changing expressions in list comprehension. 另外,请不要在列表理解中使用状态改变表达式。 A list comprehension should NOT modify any variables. 列表理解应该修改任何变量。 It is bad manners! 礼貌不好!

In your case, you'd do: 在你的情况下,你会做:

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)

Output: 输出:

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

You can do it like this 你可以这样做

myList = [['a','b','c','d'],['a','b','c','d'],['a','b','c','d']]
myOrder = [0,2,1,3] 
myList = [[sublist[i] for i in myOrder] for sublist in myList]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM