使用此表单的元素对列表进行排序('string',number)

时间:2015-04-14 07:40:15

标签: sorting python-3.x

我想以这种形式对列表进行排序:

[('Initial value problem', 0.0), 
 ('Duns Scotus', 0.0), 
 ('Open front unrounded vowel', 0.0), 
 ('Android version history', 0.0001), 
 ('Research ethics', 0.0001), 
 ('Music technology', 0.0), 
 ('Karl Bechert', 0.0001), 
 ('Motion (physics)', 0.0001), 
 ('Karl Friedrich Burdach', 0.0)]

我想根据每个元素中的数字对此列表进行排序。 感谢。

1 个答案:

答案 0 :(得分:2)

通过设置key参数

,对每个项目的第2个元素进行排序
>>> l = [('Initial value problem', 0.0), 
     ('Duns Scotus', 0.0), 
     ('Open front unrounded vowel', 0.0), 
     ('Android version history', 0.0001), 
     ('Research ethics', 0.0001), 
     ('Music technology', 0.0), 
     ('Karl Bechert', 0.0001), 
     ('Motion (physics)', 0.0001), 
     ('Karl Friedrich Burdach', 0.0)]

>>> print sorted(l, key=lambda x: x[1])

[('Initial value problem', 0.0),
 ('Duns Scotus', 0.0),
 ('Open front unrounded vowel', 0.0),
 ('Music technology', 0.0),
 ('Karl Friedrich Burdach', 0.0),
 ('Android version history', 0.0001),
 ('Research ethics', 0.0001),
 ('Karl Bechert', 0.0001),
 ('Motion (physics)', 0.0001)]

如果您希望它们按相反的顺序排列,请在调用reverse=True

时设置sorted()参数