如何读取文本文件并仅打印一列中的值高于阈值的特定行?

2024-10-02 22:34:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须读取一个逗号分隔的文本文件,如下所示:

ID, x, y, soil_temp
1, 10, 6, 8
2, 21, 11, 12
3, 11, 7, 7
4, 32, 12, 8
5, 9, 29, 6
6, 17, 16, 9
7, 22, 9, 11
8, 14, 31, 7
9, 26, 21, 6
10, 19, 19, 10

此后,我必须打印列ID和土壤温度,以及土壤温度高于10的所有行。所以结果应该是这样的:

ID, soil_temp
2, 12
7, 11

重要!不需要像熊猫和cv这样的模块,这让我很沮丧。这对这里的大多数人来说可能很容易

因此,我制作了一段代码,看起来像这样,以便能够用soil_temp打印列:

tempLine = []
with open('soil_temp.txt', 'r') as f:
    read_data = f.readlines()

for line in read_data:
    line.split()
    tempLine.append(line.split())

for item in tempLine:
    print(item[3])

本规范也基于练习中给出的建议。我的问题是,如果我只想打印10以上的行,我会认为在代码的最后一部分中有一个简单的if语句,类似这样的语句是有意义的:

for item in tempLine:
    if item[3] > 10
        print(item[3])

但这当然不起作用,因为数据存储为字符串。我尝试了不同的解决方案将它们转换成整数,但由于它是多个字符串,所以我找不到解决方案


Tags: 代码inidforreaddataifline
2条回答

我可以这样做:

with open('soil_temp.txt', 'r') as f:
    read_data = f.readlines()[1:]

id_and_temp = [(i, t)
    for i, _, _, t in (line.strip().split(", ") for line in read_data)
    if int(t) > 10
]

print("ID, soil_temp")
for i, t in id_and_temp:
    print(f"{i}, {t}")

正如其他人所指出的,你必须用逗号分开。我对您的代码做了一些修改,并使用了列表理解,使tempLine成为包含行数据的列表列表

with open('soil_temp.txt', 'r') as f:
    f.readline() # get rid of header line
    read_data = f.readlines()

tempLine = []
for line in read_data:
    tempLine.append([int(x) for x in line.split(',')]) # make a list of ints out of each dataline

print(tempLine) # to show the structure

for item in tempLine:
    if item[3] > 10:
        print(item[3])

运行它的输出将如下所示:

[[1, 10, 6, 8], [2, 21, 11, 12], [3, 11, 7, 7], [4, 32, 12, 8], [5, 9, 29, 6], [6, 17, 16, 9], [7, 22, 9, 11], [8, 14, 31, 7], [9, 26, 21, 6], [10, 19, 19, 10]]
12
11

这不是惯用的Python;我想展示如何更改现有代码以克服障碍

相关问题 更多 >