Skip to main content
 首页 » 编程设计

python之使用 '' 和 open, reader '' 功能

2024年09月07日13kuangbin

这段代码有问题:

import csv 
with open('gios-pjp-data.csv', 'r') as data: 
    l = [] 
    reader = csv.reader(data, delimiter=';')  
    next(reader)  
    next(reader)  # I need to skip 2 lines here and dont know how to do it in other way 
    l.append(# here is my problem that I will describe below) 

所以这个文件包含大约 350 行,4 列和 每个都是这样构建的:

Date ; float number ; float number ; float number 

像这样:

2017-01-01;56.7;167.2;236.9 

现在,我不知道如何构建一个将第一个 float 和第三个 float 附加到列表的函数,条件是它的值 >200。 你有什么建议吗?

请您参考如下方法:

如果文件中没有太多项目,请列出理解。

l = [x[1], x[3] for x in reader if x[1] > 200] 

或者如果您有大量条目,则类似的函数会生成每一行。

def getitems(): 
    for x in reader: 
        if x[1] > 200: 
            yield x[1], x[3] 
 
l = getitems()  # this is now an iterator, more memory efficient. 
l = list(l)  # now its a list