我认为我对 python 的理解相当不错,但这个问题让我很难过。
以下代码有效
import csv
f = open("potholes.csv")
count = 0
for row in csv.DictReader(f):
addr_bits = row['STREET ADDRESS'].split()
street_num = addr_bits[0:1]
count += 1
print type(addr_bits)
print addr_bits
print street_num
print "completed processing " + str(count) + " records"
输出:
<type 'list'>
['2519', 'S', 'HALSTED', 'ST']
['2519']
completed processing 378033 records
但是,此代码给出了错误
import csv
f = open("potholes.csv")
count = 0
for row in csv.DictReader(f):
addr_bits = row['STREET ADDRESS'].split()
street_num = addr_bits[0]
count += 1
print type(addr_bits)
print addr_bits
print street_num
print "completed processing " + str(count) + " records"
输出:
Traceback (most recent call last):
File "/home/linux/PycharmProjects/potholes/potholes", line 7, in <module>
street_num = addr_bits[0]
IndexError: list index out of range
Process finished with exit code 1
唯一的区别是第一个代码使用 [0:1] 访问此列表,第二个代码使用 [0],但我认为这是访问列表的合法方式。