簡體   English   中英

在 python 中對包含字符串和數字的元組進行排序

[英]sorting a tuple that contains string and numbers in python

我有一個這樣的清單;

List = [('apple 5', 12), ('apple 3', 2), ('apple 6', 10),('apple 4', 15), ('apple 9', 11), ('apple 7', 14), ('apple 18', 10), ('apple 16', 10),('orange 5', 4), ('orange 4', 7)]

我知道如何正常對列表進行排序。

for i in sorted(List):
  print(i)

這給出了;

('apple 16', 10)
('apple 18', 10)
('apple 3', 2)
('apple 4', 15)
('apple 5', 12)
('apple 6', 10)
('apple 7', 14)
('apple 9', 11)
('orange 4', 7)
('orange 5', 4)

但是我可以這樣排序嗎?

('apple 3', 2)
('apple 4', 15)
('apple 5', 12)
('apple 6', 10)
('apple 7', 14)
('apple 9', 11)
('apple 16', 10)
('apple 18', 10)
('orange 4', 7)
('orange 5', 4)

您只需要分配自己的key

l1 = [('apple 5', 12), ('apple 3', 2), ('apple 6', 10),('apple 4', 15), ('apple 9', 11), ('apple 7', 14), ('apple 18', 10), ('apple 16', 10),('orange 5', 4), ('orange 4', 7)]

def sort_key(x):
    word, num = x[0].split()
    return word, int(num), x[1] # Sort by word, than the number as an integer, than the final number

l1.sort(key=sort_key)
print(*l1, sep='\n')

Output:

('apple 3', 2)
('apple 4', 15)
('apple 5', 12)
('apple 7', 14)
('apple 9', 11)
('apple 16', 10)
('apple 18', 10)
('orange 4', 7)
('orange 5', 4)

您可以使用自己的鍵進行排序,並使用多個條件,語法是sorted(values, key = lambda x: (criteria_1, criteria_2))

values = [('apple 5', 12), ('apple 3', 2), ('apple 6', 10), ('apple 4', 15),
          ('apple 9', 11), ('apple 7', 14), ('apple 18', 10), ('apple 16', 10),
          ('orange 5', 4), ('orange 4', 7)]

for i in sorted(values, key=lambda x: (x[0].split(" ")[0], int(x[0].split(" ")[1]))):
    print(i)

或者使用一種方法來獲取正確的代碼

def splitter(v: str):
    s = v.split(" ")
    return s[0], int(s[1])

for i in sorted(values, key=lambda x: splitter(x[0])):
    print(i)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM