如果我有一个元素列表,例如: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
提交
取消