2016-11-24 7 views
0

私は、このお持ちの場合:整数のリストとそれに関連付けられた文字列を分けてソートするには?

[(3, 'it'), (0, 'my'), (2, 'ate'), (1, 'cat')] 

がどのように私はこの結果を得るためにそれをソートし、次に文字列から整数を分離し、することができます

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

y別の意味ですか?印刷しますか? – Bahrom

答えて

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

これを試してみてください:

(0, 'my') 
(1, 'cat') 
(2, 'ate') 
(3, 'it') 
+0

タプルをまだ印刷していない場合、タプルを展開してみませんか? – MooingRawr

0

Python的な方法、how sortingitemgetterドキュメントから:

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) 

・ホープ、このヘルプ

関連する問題