我正在用python编写一个程序,将csv转换为列表列表。它为不同的文件做了多次,所以我把它做成了一个函数。我还没有遇到过这样的错误,但我担心这是最具python/最聪明/最快的方式,因为这些都是巨大的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
必须重复两次。难道没有更优雅的解决方案吗?你知道吗
您可以在读取行时简单地进行比较,而不是先产生行,然后进行迭代。你知道吗
如果您希望进一步优化它,那么一旦找到匹配项,就可以跳出循环,前提是只有一个匹配项。你知道吗
相关问题 更多 >
编程相关推荐