【发布时间】:2013-06-22 16:42:06
【问题描述】:
我正在用 python 编写一个程序,将 csvs 转换为列表列表。它针对不同的文件多次执行此操作,因此我将其变成了一个函数。我没有遇到过这个错误,但我担心这是最 Pythonic/smartest/fastest 的方式,因为这些是巨大的 csv。
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 必须重复两次。没有更优雅的解决方案吗?
【问题讨论】:
-
你的
parseFile函数是一个生成器,所以你实际上只遍历每一行一次。您可以很好地解释什么是生成器here。 -
不,这看起来很“pythonic”生成器和上下文。 parseZips 函数看起来并没有真正发挥作用。不过其他一切看起来都不错。
标签: python csv for-loop generator yield