Python:Regex findall返回一个列表,为什么尝试访问列表元素[0]会返回错误?

2024-10-01 15:32:06 发布

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

从文档中获取的以下代码片段显示了正则表达式方法findall的工作方式,并确认它确实返回了一个列表。

re.findall(r"\w+ly", text)
['carefully', 'quickly']

但是,当试图访问findall返回的列表的第0个元素时,下面的代码片段会生成一个越界错误(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])

Tags: 方法代码recity列表withlineopen
3条回答

re.findall如果没有匹配项,则可以返回空列表。如果您尝试访问[][0],您将看到IndexError

要考虑到没有匹配项,您应该使用以下内容:

match = re.findall(...)
if match:
  # potato potato

如果没有匹配项,re.findall将返回空列表:

>>> re.findall(r'\w+ly', 'this does not work')
[]

我也有同样的问题。解决办法似乎很简单,我不知道为什么我没有考虑。

if match:

而不是

if match[0]:

相关问题 更多 >

    热门问题