如果我有一個元素列表,例如:items = ["058529-08704-200280", "058529-08704-230330", "058529-08704-140200", "058529-08704-290390", "058529-08705-140200", "058529-08705-230330", "058529-08704-170240", "058529-08705-290390", "058529-08705-170240"]我想在第二個“ - ”之后保留數字最小的元素。但是,它們必須與字符串中前兩個數字相同的元素進行比較。例如,以 開頭的字符串058529-08704,最小的數字是058529-08704-140200,對于058529-08705,最小的數字是058529-08705-140200所以最終列表必須以["058529-08704-140200", "058529-08705-140200"].什么是最 Pythonic 的方式來實現這一點,而不是編寫多個 if 或使用字符串操作?
1 回答

德瑪西亞99
TA貢獻1770條經驗 獲得超3個贊
items = ["058529-08704-200280", "058529-08704-230330", "058529-08704-140200", "058529-08704-290390",
"058529-08705-140200", "058529-08705-230330", "058529-08704-170240", "058529-08705-290390",
"058529-08705-170240"]
lst_3th_num = []
for item in items:
lst_3th_num.append(int(item.split('-')[2]))
result = []
for item in items:
if int(item.split('-')[2]) == min(int(s) for s in lst_3th_num):
result.append(item)
print(result)
添加回答
舉報
0/150
提交
取消