我在 python 中有一个这样的列表
list = ['1', '1.1', '1.2', '1.3','1.4', '2', '2.1', '2.2', '3', '3.1', '3.2']
我能得到这个结果吗
['1', '1.4', '2', '2.2', '3', '3.2']
或
['1.4', '2.2', '3.2']
这是一个字符串格式的任务列表,我需要获取每个父任务下的最后一个子任务。
谢谢
请您参考如下方法:
首先你需要定义比较函数:
def cmp_tasks(a,b):
a = a.split('.')
b = b.split('.')
if len(a) == len(b):
ret = cmp(int(a[0]),int(b[0]))
if not ret:
return cmp(int(a[1]),int(b[1]))
return ret
else:
return cmp(int(a[0]),int(b[0]))
然后:
一条线:
您可以在一个类轮中完成此操作:
>>> {int(float(i)):i for i in sorted(l,cmp=cmp_tasks)}.values()
['1.30', '2.2', '3.2']
详细做法:
或者,更详细地说:您首先需要根据底值对值进行分组:
l = ['1', '1.30', '1.1', '1.2', '1.3','1.4', '2', '2.1', '2.2', '3', '3.1', '3.2']
groups = {}
for i in l:
groups.setdefault(int(float(i)),[]).append(i)
现在
>>> groups
{1: ['1','1.30', '1.1', '1.2', '1.3', '1.4'], 2: ['2', '2.1', '2.2'], 3: ['3', '3.1', '3.2']}
然后你可以从每组中取最大值:
>>> [sorted(g,cmp=cmp_tasks)[-1] for g in groups.values()]
['1.30', '2.2', '3.2']
附注 请注意,覆盖 list 关键字不是一个好主意,因为之后您将无法使用 list
