gpt4 book ai didi

python - 快速打开和关闭csv?

转载 作者:太空宇宙 更新时间:2023-11-03 18:55:45 29 4
gpt4 key购买 nike

我正在用 python 编写一个程序,将 csv 转换为列表列表。它对不同的文件多次执行此操作,因此我将其放入一个函数中。我还没有遇到过这样的错误,但我担心这是最Pythonic/最智能/最快的方法,因为这些是巨大的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 必须重复两次。难道就没有更优雅的解决方案吗?

最佳答案

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

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]

关于python - 快速打开和关闭csv?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17304886/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com