访问特定列表项时出现问题

Problems accessing specific list item

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

那是因为有时行 ['STREET ADDRESS'] 是空的,使得 row['STREET ADDRESS'].split() return 成为一个空列表

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

这里有一个例子:

In [10]: x = []

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

In [12]: x[0] # this will raise an error