【问题标题】:Pythonic way to sort on tuple, dict item and convert to array [duplicate]Pythonic方式对元组,字典项进行排序并转换为数组[重复]
【发布时间】:2016-08-09 13:55:46
【问题描述】:

给定这个元组数组

[('h1', 0.522611856461), ('h2', 0.438368797302), ('h3', 0.443703174591)]

或者给定这本词典

{'h2': 0.438368797302, 'h3': 0.443703174591, 'h1': 0.522611856461}

如何创建一个由“h”项['h2', 'h3', 'h1'] 组成的数组,按浮动项排序?

【问题讨论】:

标签: python sorting dictionary tuples


【解决方案1】:

对于列表:

>>> from operator import itemgetter
>>> l = [('h1', 0.522611856461), ('h2', 0.438368797302), ('h3', 0.443703174591)]
>>> [x[0] for x in sorted(l, key=itemgetter(1))]
['h2', 'h3', 'h1']

【讨论】:

    猜你喜欢
    • 2020-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-15
    • 2014-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多