2016-11-09 74 views
-1

说完看着蟒蛇3文档,我想尝试类似的东西交换嵌套列表的Python 3

nested_list = [ 
(1,4,7,10), 
(2,5,8,11), 
(3,6,9,12), 
] 
sorted(nested_list, key=lambda nes: nes[0]) 

print(nested_list) 

我希望清单作为输出:

[(2, 5, 8, 11), (1, 4, 7, 10), (3, 6, 9, 12)] 

而是将其输出为:

[(1, 4, 7, 10), (2, 5, 8, 11), (3, 6, 9, 12)] 

这是一样的!

我使用Python 3.5.1顺便说一句。

+0

好的,你排序的第一个元素的列表。这是正确的顺序。应该如何排序列表? –

+0

您希望的输出的排序标准是什么? “排序”就是这样做的,排序。 –

+0

什么这么难理解? TallChuck明白了 –

回答

0

'key'参数需要一个函数,并且该函数在迭代时作为参数传递给数组的每个元素。在nested_list线

sorted(nested_list, key=lambda nes: nes[0]) 

着眼于每一个元组,将其分配给nesnes[0]进行排序。如果你想基于别的东西对它进行排序,说每个数组的最后一个索引,你将其更改为

sorted(nested_list, key=lambda nes: nes[-1]) 

如果你想要做的是交换的nested_list前两元组,我只想建议说

nested_list[0], nested_list[1] = nested_list[1], nested_list[0] 
+0

谢谢!有效!!!事实证明,我只是想交换前两个元组哈哈 –

+0

如果我尝试用字符串它不起作用,我得到一个类型错误? –

+0

你使用了什么命令? – TallChuck