0

我正在尝试遍历此文本文件,拆分文本并将高温和低温的数据提取到 2 个单独的列表中:我有以下代码,它给了我高温,但我坚持我所缺少的得到低温。有人可以解释我在这里出错的地方吗?提前感谢您的帮助。

high =[]
low =[]
line =''

inFile = open('julyTemps.txt')

for line in inFile:
    fields = line.split(' ')

with open ('julyTemps.txt') as inFile:
    if fields != 3 or 'Boston' == fields[0] or 'Day' == fields[0]:
        high = (line.split(' ')[1:2] for line in inFile)
        high =[item[0] for item in high if item]
        high = ','.join([i for i in high if i.isdigit()])
with open ('julyTemps.txt') as inFile:
    if fields != 3 or 'Boston' == fields[0] or 'Day' == fields[0]:
        low = (line.split(' ')[2:2] for line in inFile)
        low = [item[0] for item in low if item]
        low =','.join([i for i in low if i.isdigit()])

txt文件:

Boston July Temperatures
-------------------------

Day High Low
------------

1 91 70
2 84 69
3 86 68
4 84 68
5 83 70
6 80 68
7 86 73
8 89 71
9 84 67
10 83 65
11 80 66
12 86 63
13 90 69
14 91 72
15 91 72 
16 88 72
17 97 76
18 89 70
19 74 66
20 71 64
21 74 61
22 84 61
23 86 66
24 91 68
25 83 65
26 84 66
27 79 64
28 72 63
29 73 64
30 81 63
31 73 63
4

1 回答 1

2

只需将文件合二为一,将低点和高点添加到两个单独的列表中:

lows, highs = [], []
with open ('julyTemps.txt') as inFile:
    for line in inFile:
        try:
            day, low, high = map(int, line.split())
        except ValueError:
            continue  # no temps on this line
        lows.append(low)
        highs.append(high)

我们只查看具有 3 个整数值的行,其余的会抛出 a ValueError,因为该行没有 3 个值,或者因为存在非整数值。这些行被忽略。

于 2013-04-01T21:33:03.183 回答