1

我认为我对 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],但我认为这是访问列表的合法方式。

4

1 回答 1

4

那是因为有时 row['STREET ADDRESS'] 是空的,因此row['STREET ADDRESS'].split()返回一个空列表

您可以访问带有切片但不能索引特定元素的空列表。

这是一个例子:

In [10]: x = []

In [11]: x[0:1] # this returns empty list
Out[11]: []

In [12]: x[0] # this will raise an error
于 2015-09-26T14:16:31.363 回答