如果我有这个:
[(3, 'it'), (0, 'my'), (2, 'ate'), (1, 'cat')]
如何将整数与字符串分开,然后对其进行排序以获得此结果:
0 'my'
1 'cat'
2 'ate'
3 'it'
答案 0 :(得分:0)
试试这个:
x = sorted([(3, 'it'), (0, 'my'), (2, 'ate'), (1, 'cat')])
for i in x:
print(i)
输出:
(0, 'my')
(1, 'cat')
(2, 'ate')
(3, 'it')
答案 1 :(得分:0)
来自文档的Pythonic方式,how sorting,itemgetter
:“返回一个可获取项目的可调用对象”
L = [(3, 'it'), (0, 'my'), (2, 'ate'), (1, 'cat')]
from operator import itemgetter
print ( "\n".join(map(lambda x: "%d '%s'" % x, sorted(L, key=itemgetter(0)))))
你明白了,
0 'my'
1 'cat'
2 'ate'
3 'it'
答案 2 :(得分:0)
只需对元组列表进行排序,然后打印格式化:
>>> tuples = [(3, 'it'), (0, 'my'), (2, 'ate'), (1, 'cat')]
>>> tuples = sorted(tuples)
>>> for tup in tuples:
print("{} '{}'".format(*tup))
0 'my'
1 'cat'
2 'ate'
3 'it'
>>>
答案 3 :(得分:0)
尝试以下方法:
l = [(3, 'it'), (0, 'my'), (2, 'ate'), (1, 'cat')]
for item in sorted(l):
print("{} '{}'".format(item[0], item[1]))
<强>输出:强>
0 'my'
1 'cat'
2 'ate'
3 'it'
答案 4 :(得分:0)
我在... How can I sort a dictionary by key?
上找到了您的问题的答案使用该代码,我开发了以下内容:
#!/usr/bin/python3
# StackOverflow answer sample to question:
# How to separate and sort a list of integers and it's associated string?
# Author: RJC (aka mmaurice)
# Question input: [(3, 'it'), (0, 'my'), (2, 'ate'), (1, 'cat')]
# Question expected output:
# 0 'my'
#
# 1 'cat'
#
# 2 'ate'
#
# 3 'it'
import collections
test_dict = dict([(3, 'it'), (0, 'my'), (2, 'ate'), (1, 'cat')])
print(test_dict) #not in order
#use collections to sort the dictionary.
od_test_dict = collections.OrderedDict(sorted(test_dict.items()))
for k, v in od_test_dict.items(): print(k, v)
希望这有帮助