Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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_List_Sorting_Nested - Fatal编程技术网

如何对python列表进行排序?

如何对python列表进行排序?,python,list,sorting,nested,Python,List,Sorting,Nested,我有一个以下格式的python嵌套列表。我需要根据第三个条目对列表进行排序 interactions = [[0 for x in xrange(3)] for x in xrange(3) ] interactions[0] = 'TP53', 'BRCA2', 0.5 interactions[1] = 'AGT' , 'PCALM', 0.8 interactions[2] = 'BRCA1', 'BRCA2',0.2 我想根据第三个条目对列表进行排序,即浮点值。请建议一种有效的

我有一个以下格式的python嵌套列表。我需要根据第三个条目对列表进行排序

 interactions = [[0 for x in xrange(3)] for x in xrange(3) ]
 interactions[0] = 'TP53', 'BRCA2', 0.5
 interactions[1] = 'AGT' , 'PCALM', 0.8
 interactions[2] = 'BRCA1', 'BRCA2',0.2
我想根据第三个条目对列表进行排序,即浮点值。请建议一种有效的方法。

或接受可选的
功能。键函数的返回值用作比较键

>>> interactions = [[0 for x in xrange(3)] for x in xrange(3) ]
>>> interactions[0] = 'TP53', 'BRCA2', 0.5
>>> interactions[1] = 'AGT' , 'PCALM', 0.8
>>> interactions[2] = 'BRCA1', 'BRCA2',0.2
>>> interactions.sort(key=lambda i: i[2])
>>> interactions
[('BRCA1', 'BRCA2', 0.2), ('TP53', 'BRCA2', 0.5), ('AGT', 'PCALM', 0.8)]
您还可以使用来代替:

或接受可选的
功能。键函数的返回值用作比较键

>>> interactions = [[0 for x in xrange(3)] for x in xrange(3) ]
>>> interactions[0] = 'TP53', 'BRCA2', 0.5
>>> interactions[1] = 'AGT' , 'PCALM', 0.8
>>> interactions[2] = 'BRCA1', 'BRCA2',0.2
>>> interactions.sort(key=lambda i: i[2])
>>> interactions
[('BRCA1', 'BRCA2', 0.2), ('TP53', 'BRCA2', 0.5), ('AGT', 'PCALM', 0.8)]
您还可以使用来代替:

有一个
参数,您可以在其中传入任何函数。在本例中,创建一个短内联函数(称为a),该函数返回元组中的第三个元素:

interactions.sort(key=lambda x:x[2])
有一个
参数,您可以在其中传入任何函数。在本例中,创建一个短内联函数(称为a),该函数返回元组中的第三个元素:

interactions.sort(key=lambda x:x[2])

一个建议。创建如下列表
interactions=[]
,然后使用
interactions.append
将元素添加到列表中。现在,您正在创建一个2D列表,并用元组替换所有内部列表。一个建议。创建如下列表
interactions=[]
,然后使用
interactions.append
将元素添加到列表中。现在,您正在创建一个二维列表,并用元组替换所有内部列表。