1

我正在开发一个将 csvs 转换为列表列表的 python 程序。它针对不同的文件多次执行此操作,因此我将其变成了一个函数。我没有遇到这个错误,但我担心这是最 Pythonic/smartest/fastest 的方式,因为这些是巨大的 csvs。

import csv

searchZipCode = #there's a zip code here
zipCoords = #there's a file here

def parseFile(selected):
    with open(selected) as selectedFile:
            selectedReader = csv.reader(selectedFile, delimiter=',')
            for row in selectedReader:
                    yield row

def parseZips():
    return parseFile(zipCoords)

zips = parseZips()
for row in zips:
    if row[0] == searchZipCode:
            searchState = row[1]
            searchLat   = row[2]
            searchLong  = row[3]
            print searchState 

基本上,我想知道为什么for row必须重复两次。没有更优雅的解决方案吗?

4

1 回答 1

1

您可以在读取行时简单地进行比较,而不是产生然后迭代。

def findZip(selected, search):
    results = []
    with open(selected) as file:
        handle = csv.reader(file, delimiter=',')
        for row in handle:
            if row[0] == search
                results.append(row[1:4])
    return results

如果您希望进一步优化它,您可以在找到匹配项后跳出循环,前提是只有一个匹配项。

def findZip(selected, search):
    with open(selected) as file:
        handle = csv.reader(file, delimiter=',')
        for row in handle:
            if row[0] == search
                return row[1:4]
于 2013-06-25T18:40:06.760 回答