Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中对列表进行排序?_Python_Sorting_Python 2.7 - Fatal编程技术网

如何在Python中对列表进行排序?

如何在Python中对列表进行排序?,python,sorting,python-2.7,Python,Sorting,Python 2.7,我有一个嵌套列表 a=[[x1,y1],[x2,y2],[x1,y2],[x2,y1],[x7,y7],[x1,y3]] 我想把它分类为: a=[[x1,y1],[x1,y2],[x1,y3],[x2,y1],[x2,y2],[x7,y7]] 我尝试使用lambda函数,但无法编译: a=sorted(a,lambda x,y:x==y?x[0]+x[1],x[0]) 如何使用排序的获得所需的输出?您可以使用实际的Python语法,例如: 这基于将?语法解释为Javascript条件表达式

我有一个嵌套列表

a=[[x1,y1],[x2,y2],[x1,y2],[x2,y1],[x7,y7],[x1,y3]]
我想把它分类为:

a=[[x1,y1],[x1,y2],[x1,y3],[x2,y1],[x2,y2],[x7,y7]]
我尝试使用lambda函数,但无法编译:

a=sorted(a,lambda x,y:x==y?x[0]+x[1],x[0])

如何使用排序的获得所需的输出?

您可以使用实际的Python语法,例如:

这基于将
语法解释为Javascript条件表达式语法

当然,这假设在某个地方定义了一个单独的
y
变量:

>>> a = [[1,1], [2,2], [1,2], [2,1], [7,7], [1,3]]
>>> y = [1, 1]
>>> sorted(a, key=lambda x: x[0] + x[1] if x == y else x[0])
[[1, 2], [1, 3], [1, 1], [2, 2], [2, 1], [7, 7]]
我相信,
sorted(a)
将立即满足您的需求:

>>> a = [[1,1], [2,2], [1,2], [2,1], [7,7], [1,3]]
>>> sorted(a)
[[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [7, 7]]

您是否可以展示一个实际的、可运行的示例,并解释默认排序以何种方式不能满足您的需要?我想看看是否可以使用lambda函数实现上述功能question@learner:由于语法不正确,我们只是猜测您想要什么。您需要更明确地说明排序的行为方式。我发现这个Martjin有一个错误——看起来lambda缺少一个位置参数。
>>> a = [[1,1], [2,2], [1,2], [2,1], [7,7], [1,3]]
>>> sorted(a)
[[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [7, 7]]