Python 获取包含整数和浮点数的列表最大值的方法
Python way of getting max of list containing integers and floats
我在 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']
p.s.
请注意,覆盖 list
关键字不是一个好主意,因为之后您将无法使用 list
简单的 itertools 解决方案:
import itertools
l = ['1', '1.1', '1.2', '1.3','1.4', '2', '2.1', '2.2', '3', '3.1', '3.2', '11', '11.1']
assert [list(group)[-1] for category, group in itertools.groupby(l, lambda x: x.split('.')[0])] == ['1.4', '2.2', '3.2', '11.1']
对于不同形式的输入数据,应更改 lambda 函数。
我在 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']
p.s.
请注意,覆盖 list
关键字不是一个好主意,因为之后您将无法使用 list
简单的 itertools 解决方案:
import itertools
l = ['1', '1.1', '1.2', '1.3','1.4', '2', '2.1', '2.2', '3', '3.1', '3.2', '11', '11.1']
assert [list(group)[-1] for category, group in itertools.groupby(l, lambda x: x.split('.')[0])] == ['1.4', '2.2', '3.2', '11.1']
对于不同形式的输入数据,应更改 lambda 函数。