如果我有這樣的:如何分離和排序整數列表及其關聯字符串?
[(3, 'it'), (0, 'my'), (2, 'ate'), (1, 'cat')]
我怎樣才能整數從字符串分開,然後對其進行排序,以得到這樣的結果:
0 'my'
1 'cat'
2 'ate'
3 'it'
如果我有這樣的:如何分離和排序整數列表及其關聯字符串?
[(3, 'it'), (0, 'my'), (2, 'ate'), (1, 'cat')]
我怎樣才能整數從字符串分開,然後對其進行排序,以得到這樣的結果:
0 'my'
1 'cat'
2 'ate'
3 'it'
嘗試以下操作:
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'
試試這個:
x = sorted([(3, 'it'), (0, 'my'), (2, 'ate'), (1, 'cat')])
for i in x:
print(i)
輸出:
(0, 'my')
(1, 'cat')
(2, 'ate')
(3, 'it')
爲什麼不打開元組,如果你已經打印出來了? – MooingRawr
Python的方式,how sorting,itemgetter
從文件: 「返回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'
簡單排序元組的列表,並把它們格式化打印:
>>> 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'
>>>
我找到了答案對你的問題...... 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)
希望這幫助
y你的意思是分開的?打印它? – Bahrom