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

2024-04-26 02:53:41 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: csv代码instreettypecountnumbits
1条回答
网友
1楼 · 发布于 2024-04-26 02:53:41

这是因为有时行['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

相关问题 更多 >