按第二项(整数值)对元组列表进行排序我有一个元组列表,如下所示:[('abc', 121),('abc', 231),('abc', 148), ('abc',221)]我希望按照元组内的整数值对此列表进行升序排序。有可能吗?
3 回答

开满天机
TA贡献1786条经验 获得超13个赞
key
sorted()
.
sorted([('abc', 121),('abc', 231),('abc', 148), ('abc',221)], key=lambda x: x[1])
key
[1]
.
itemgetter(1)
lambda x: x[1]
.

一只斗牛犬
TA贡献1784条经验 获得超2个赞
>>> from operator import itemgetter>>> data = [('abc', 121),('abc', 231),('abc', 148), ('abc',221)]>>> sorted(data,key=itemgetter(1))[('abc', 121), ('abc', 148), ('abc', 221), ('abc', 231)]
itemgetter
c
lambda
.
>python -m timeit -s "from operator import itemgetter; data = [('abc', 121),('abc', 231),('abc', 148), ('abc',221)]" "sorted(data,key=itemgetter(1))"1000000 loops, best of 3: 1.22 usec per loop>python -m timeit -s "data = [('abc', 121),('abc', 231),('abc', 148), ('abc',221)]" "sorted(data,key=lambda x: x[1])"1000000 loops, best of 3: 1.4 usec per loop

RISEBY
TA贡献1856条经验 获得超5个赞
data = [('abc', 121),('abc', 231),('abc', 148), ('abc',221)]
sorted()
添加回答
举报
0/150
提交
取消