我在理解Python 函式中的key引數時遇到問題sorted。讓我們說,給出了以下串列:sample_list = ['Date ', 'of', 'birth', 'year 1990', 'month 10', 'day 15']我只想對包含數字的字串進行排序。
預期輸出: ['Date ', 'of', 'birth', 'month 10', 'day 15', 'year 1990']
到現在為止,我只設法列印帶有數字的字串
def sort_with_key(element_of_list):
if re.search('\d ', element_of_list):
print(element_of_list)
return element_of_list
sorted(sample_list, key = sort_with_key)
但是我實際上如何對這些元素進行排序?謝謝!
uj5u.com熱心網友回復:
我們可以嘗試使用 lambda 進行排序:
sample_list = ['Date ', 'of', 'birth', 'year 1990', 'month 10', 'day 15']
sample_list = sorted(sample_list, key=lambda x: int(re.findall(r'\d ', x)[0]) if re.search(r'\d ', x) else 0)
print(sample_list)
這列印:
['Date ', 'of', 'birth', 'month 10', 'day 15', 'year 1990']
如果條目有數字,則 lambda 中使用的邏輯是按每個串列條目中的數字排序。否則,它會為其他條目分配零值,將它們放在排序的最前面。
uj5u.com熱心網友回復:
如果我理解正確,您是否希望以該數字為關鍵字對帶有數字的字串進行排序,而將沒有數字的字串放在開頭?
您需要一個從字串中提取數字的鍵。我們可以使用str.isdigit()從字串中提取數字,''.join()將這些數字重新組合在一起,并int()轉換為整數。如果字串中沒有數字,我們將-1改為回傳,因此它位于所有非負數之前。
sample_list = ['Date ', 'of', 'birth', 'year 1990', 'month 10', 'day 15', 'answer 42', 'small number 0', 'large number 8676965', 'no number here']
sample_list.sort(key=lambda s: int(''.join(c for c in s if c.isdigit()) or -1))
print(sample_list)
# ['Date ', 'of', 'birth', 'no number here', 'small number 0', 'month 10', 'day 15', 'answer 42', 'year 1990', 'large number 8676965']
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/379978.html
上一篇:Mysql按陣列中的值排序
下一篇:二叉樹不插入或搜索節點
