使用Python返回CSV中给定行的索引[0]值

时间:2016-12-15 12:03:39

标签: python

我可以在Python中使用with open来迭代逗号Sep文本文件,但我希望增加另一层复杂性。 我需要返回找到字符串的行的index[0]处的值。

例如,我有一个包含以下内容的文本文件:

00:00,19.90,990.49,59.16,11.78,No
01:00,19.92.991.00,59.75,11.90,Yes
02:00,19.76,991.21,58.87,10.95,No
03:00,19.34,989.97,57.00,10.64,Yes

现在我使用:

MaxTemp = -float('inf')
MinTemp = +float('inf')
with open (YdPath + yFileDate + '.txt', 'r') as DailyData:
    for lines in DailyData:
        temp = float(lines.strip().split(',')[1])
        if MaxTemp < temp:
            MaxTemp = temp
        if MinTemp > temp:
            MinTemp = temp

,输出为:

MaxTemp = 19.92
MinTemp = 19.34

现在虽然我希望获得与这些条目相关的index[0]值,即

MaxTemp需要找到以{00}的index[0]开头的行中的条目19.92&amp;使用变量tTime作为index[0]值:

显示
print 'The Max Temp was ' + MaxTemp + ' recorded at ' +  tTime 

感谢您寻找

更新

感谢Henry Heath寻求帮助&amp;指针。

需要2个时间变量MaxTemp&amp; MinTemp使用tTime返回完全相同的时间,这是正确的工作代码:

MaxTemp = -float('inf')
MinTemp = +float('inf')

with open (YdPath + yFileDate + '.txt', 'r') as DailyData:
    for line in DailyData:
        line = line.strip().split(',')
        temp = float(line[1])
        if MaxTemp < temp:
            MaxTemp = temp
            MXtTime = line[0]
        if MinTemp > temp:
            MinTemp = temp
            MNtTime = line[0]

MaxTemps = '%.1f' %MaxTemp
MinTemps = '%.1f' %MinTemp

print('The Max Temp was ' + MaxTemps + ' recorded at ' + MXtTime)
print('The Min Temp was ' + MinTemps + ' recorded at ' + MNtTime)

2 个答案:

答案 0 :(得分:1)

如果您使用csv

,这可能会更容易
MaxTemp = -float('inf')
MinTemp = +float('inf')
with open (YdPath + yFileDate + '.txt', 'r') as DailyData:
    for line in DailyData:
        line = line.strip().split(',')
        temp = float(line[1])
        if MaxTemp < temp:
            MaxTemp = temp
            tTime = line[0]
        if MinTemp > temp:
            MinTemp = temp

答案 1 :(得分:0)

跟进@ henry-heath的建议:

import csv
from decimal import Decimal

# n.b., this implementation uses a sort for the brevity of 
# implementation.  However, the original iterative approach 
# will be much faster (O(n) compared to O(n log n)) than
# the version below
with open (YdPath + yFileDate + '.txt', 'r') as f:
    reader = csv.reader(f)
    lines = [line for line in reader]
    lines.sort(key=lambda x: Decimal(x[1]))
    print 'The Max Temp was ' + lines[-1][1] + ' recorded at ' +  lines[-1][0]
    print 'The Min Temp was ' + lines[0][1] + ' recorded at ' + lines[0][0] 

迭代版本:

import csv
from decimal import Decimal

with open (YdPath + yFileDate + '.txt', 'r') as f:
    reader = csv.reader(f)
    line = reader.next()
    line[1] = Decimal(line[1])
    min_temp, max_temp = line, line
    for x in reader:
        x[1] = Decimal(x[1])
        if x[1] < min_temp[1]: min_temp = x
        if x[1] > max_temp[1]: max_temp = x       
    print 'The Max Temp was ' + max_temp[1] + ' recorded at ' +  max_temp[0]
    print 'The Min Temp was ' + min_temp[1] + ' recorded at ' + min_temp[0]