我必须读取一个逗号分隔的文本文件,如下所示:
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])
但这当然不起作用,因为数据存储为字符串。我尝试了不同的解决方案将它们转换成整数,但由于它是多个字符串,所以我找不到解决方案
我可以这样做:
正如其他人所指出的,你必须用逗号分开。我对您的代码做了一些修改,并使用了列表理解,使
tempLine
成为包含行数据的列表列表运行它的输出将如下所示:
这不是惯用的Python;我想展示如何更改现有代码以克服障碍
相关问题 更多 >
编程相关推荐