2016-11-24 32 views

回答

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' 
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') 
+0

爲什麼不打開元組,如果你已經打印出來了? – MooingRawr

0

Python的方式,how sortingitemgetter從文件: 「返回Callable對象獲取項目」

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' 
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' 
>>> 
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) 

希望這幫助

相關問題