Python: Regex findall 返回列表,为什么访问元素 [0] 会报错?
以下内容摘自文档,展示了正则表达式方法 findall 的用法,并确认它确实会返回一个列表。
re.findall(r"\w+ly", text)
['carefully', 'quickly']
但是,下面这段代码在尝试访问 findall 返回的列表的第一个元素时,会出现越界错误(IndexError: list index out of range
)。
相关代码片段:
population = re.findall(",([0-9]*),",line)
x = population[0]
thelist.append([city,x])
为什么会发生这种情况呢?
为了提供更多背景信息,这段代码是我整个脚本的一部分:
import re
thelist = list()
with open('Raw.txt','r') as f:
for line in f:
if line[1].isdigit():
city = re.findall("\"(.*?)\s*\(",line)
population = re.findall(",([0-9]*),",line)
x = population[0]
thelist.append([city,x])
with open('Sorted.txt','w') as g:
for item in thelist:
string = item[0], ', '.join(map(str, item[1:]))
print string
编辑:请查看下面的评论,了解为什么会发生这种情况。我快速解决的方法是:
if population:
x = population[0]
thelist.append([city,x])
3 个回答
1
我之前也遇到过这个问题。解决办法看起来很简单,我也不知道为什么我没有想到。
if match:
而不是
if match[0]:
3
re.findall
这个函数在没有找到匹配项的时候,会返回一个空列表。如果你试图访问这个空列表的第一个元素,比如 [][0]
,就会出现 IndexError
的错误。
为了处理没有匹配项的情况,你可以使用类似下面的方式:
match = re.findall(...)
if match:
# potato potato
12
re.findall
这个函数如果没有找到匹配的内容,就会返回一个空的列表:
>>> re.findall(r'\w+ly', 'this does not work')
[]