sorted
不修改原始列表,它返回一个新的排序版本List
。您应该将返回的列表分配sorted
给一个变量:
>>> lis = [('a', Decimal('1420.3345345278832575')), ('b', Decimal('380.0000000000000000')),('c', Decimal('382.0000000000000000'))]
>>> new_lis = sorted(lis, key=itemgetter(1))
>>> new_lis
[('b', Decimal('380.0000000000000000')), ('c', Decimal('382.0000000000000000')), ('a', Decimal('1420.3345345278832575'))]
或对原始列表进行排序,请使用list.sort
:
>>> lis = [('a', Decimal('1420.3345345278832575')), ('b', Decimal('380.0000000000000000')),('c', Decimal('382.0000000000000000'))]
>>> lis.sort(key=itemgetter(1))
>>> lis
[('b', Decimal('380.0000000000000000')), ('c', Decimal('382.0000000000000000')), ('a', Decimal('1420.3345345278832575'))]