使用for循环分配列表项会导致无限循环

时间:2018-08-08 00:47:35

标签: python python-3.x for-loop counter infinite-loop

我有一个文件,其中包含美国的所有邮政编码以及它们的纬度和经度。该文件的格式为ZIP,LAT, LONG\n

我打算将它们保存到数据库中,因此我逐字遍历了文件并设置了counter变量。如果counter == 1应该将值分配给zip_codes[],如果counter == 2将值分配给latitude[]并且如果counter == 3将值分配给longitude[],但是,当我运行以下代码来测试它是否正确添加了邮政编码值时,它变成了一个无限循环,我不得不强制退出IDLE

(可以在here上查看文件)

zip_code_file = open('zip_codes.txt')
zip_codes=[]
latitude=[]
longitude = []
counter = 1
for s in zip_code_file.read().split(','):
    s = s.strip()
    if counter ==1: 
        zip_codes.append(s)
        counter = counter +1
    elif counter == 2:
        latitude.append(s)
        counter = counter+1
    elif counter == 3:
        longitude.append(s)
        counter = 1
print(zip_codes)

有人知道这是怎么回事吗?

2 个答案:

答案 0 :(得分:2)

您需要少一点循环:

zip_code_file = open('zip_codes.txt')
zip_codes = []
latitude = []
longitude = []
for line in zip_code_file:
    zipcode, lat, lng = line.strip().split(',')
    zip_codes.append(zipcode)
    latitude.append(lat)
    longitude.append(lng)
print(zip_codes)

答案 1 :(得分:1)

逗号分隔值的文件应使用csv模块

进行处理
import csv

with open('zip_codes.txt') as f:
    r = csv.reader(f)
    next(r)  # skip the header
    zip_codes, latitudes, longitudes = zip(*r)