查找特定的最大值

时间:2014-08-25 04:34:34

标签: python string list

我有一串数据,列表中有温度,时间和其他数字。现在我想找到最高温度和最高温度发生的时间。我只能找到最大值,这个数字属于我不关心atm的其他数字。

>>> s = re.findall('\d+',data)
>>> max.s

这就是我找到最大值的方式。有没有办法获得最高温度。 数据按时间排序,一些样本数据。

    05:00,9.0,0.0,0,0,0,0,0,0,0,19,31
    05:01,9.0,0.0,0,0,0,0,0,0,0,20,30
    05:02,8.9,0.0,0,0,0,0,0,0,0,19,29
    05:03,8.9,0.0,0,0,0,0,0,0,0,19,30
    05:04,9.0,0.0,0,0,0,0,0,0,0,18,21
    05:05,9.0,0.0,0,0,0,0,0,0,0,17,26
    05:06,9.0,0.0,0,0,0,0,0,0,0,17,25
    05:07,9.0,0.0,0,0,0,0,0,0,0,17,30
    05:08,9.0,0.0,0,0,0,0,0,0,0,18,29
    05:09,9.0,0.0,0,0,0,0,0,0,0,17,33
    05:10,9.0,0.0,0,0,0,0,0,0,0,18,28

所以我希望得到记录最高温度的时间。

感谢您的帮助!!

2 个答案:

答案 0 :(得分:0)

您可以在此处使用max()来获取最高温度,然后稍后迭代每一行以获取时间:

>>> s = '''05:00,9.0,0.0,0,0,0,0,0,0,0,19,31
05:01,9.0,0.0,0,0,0,0,0,0,0,20,30
05:02,8.9,0.0,0,0,0,0,0,0,0,19,29
05:03,8.9,0.0,0,0,0,0,0,0,0,19,30
05:04,9.0,0.0,0,0,0,0,0,0,0,18,21
05:05,9.0,0.0,0,0,0,0,0,0,0,17,26
05:06,9.0,0.0,0,0,0,0,0,0,0,17,25
05:07,9.0,0.0,0,0,0,0,0,0,0,17,30
05:08,9.0,0.0,0,0,0,0,0,0,0,18,29
05:09,9.0,0.0,0,0,0,0,0,0,0,17,33'''
>>> data = s.splitlines()      #splits data into lines
>>> max_temp = max(data, key=lambda x:float(x.split(',')[1])).split(',')[1]
>>> max_temp
'9.0'
>>> [x[0] for x in (line.split(',') for line in data) if max_temp == x[1]]
['05:00', '05:01', '05:04', '05:05', '05:06', '05:07', '05:08', '05:09']

答案 1 :(得分:0)

试试这个:

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import re

res = []
t = []
a = ['05:00,9.0,0.0,0,0,0,0,0,0,0,19,31',
     '05:01,9.0,0.0,0,0,0,0,0,0,0,20,30']
for i in a:
    res.append(re.findall('\d+:\d+', i)[0])
    res.append(re.findall('\d+\.\d+', i)[0])

temp = res[1::2]


maxTemp = max(temp)

for i in xrange(1, len(res), 2):
    if res[i] == maxTemp:
        t.append(res[i-1])
print 'final result is ', (maxTemp, t)