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

Python 访问特定列表项时出现问题,python,list,indexoutofrangeexception,Python,List,Indexoutofrangeexception,我认为我在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 pr

我认为我在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
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
输出:

<type 'list'>
['2519', 'S', 'HALSTED', 'ST']
['2519']
completed processing 378033 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
回溯(最近一次呼叫最后一次):
文件“/home/linux/PycharmProjects/pottholes/pottholes”,第7行,在
street_num=地址位[0]
索引器:列表索引超出范围
进程已完成,退出代码为1

唯一的区别是,第一个代码使用[0:1]来访问此列表,第二个代码使用[0],但我认为这是访问列表的合法方式。

这是因为有时行['STREET ADDRESS']是空的,使得
行['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

这是因为有时行['STREET ADDRESS']是空的,使得
行['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

如果
thing[0]
索引器
,则
thing
的长度为零<代码>东西[:1](
0
是默认开始)仍将工作,但长度也将为零<代码>[][:1]=[]。如果有一个空行,请使用
如果addr\u bits:street\u num=addr\u bits[0]
,它们也返回不同的内容,因此代码不可比较,第一个返回列表片段,第二个返回单个元素,因此即使没有错误,您的代码也不是相同的
内容[0]
索引器,那么
东西
就是零长度<代码>东西[:1]
0
是默认开始)仍将工作,但长度也将为零<代码>[][:1]=[]。如果有一个空行,请使用
如果addr\u bits:street\u num=addr\u bits[0]
,它们都返回不同的内容,因此代码不具有可比性,第一个返回列表片段,第二个返回单个元素,因此即使没有错误,您的代码也不相同。谢谢,我添加了一个try/except,它现在正在工作。我会尽快接受这个答案。我会做
len(x)>0
而不是尝试,只是有点cleaner@DorElias请注意,
if len(x)>0:
通常只写
if x:
cleaner!谢谢,我已经添加了一个try/except,现在可以使用了。我会尽快接受这个答案。我会做
len(x)>0
而不是尝试,只是有点cleaner@DorElias请注意,
if len(x)>0:
通常只写
if x:
cleaner!