【问题标题】:append lists recursively in python在python中递归地追加列表
【发布时间】:2015-06-30 13:39:21
【问题描述】:

我有一个循环。每次循环运行时,都会创建一个新列表。我想将所有这些列表添加在一起。我的代码如下:

while i < len(symbolslist):

    html_text = urllib.urlopen('my-url.com/'+symbolslist[i]).read()
    pattern = re.compile('<a target="_blank" href="(.+?)" rel="nofollow"')
    applink = re.findall(pattern, htmltext)
    applink += applink
    i+=1

其中 applink 是一个列表。但是,使用我拥有的当前代码,它只会将最后两个列表添加在一起。我做错了什么?

谢谢!

【问题讨论】:

  • applink = re.findall(pattern,htmltext) <...> applink += applink

标签: python list append


【解决方案1】:

问题是您使用 applink 作为变量名来存储 re.findall() 返回的列表,因此您最终每次都创建一个新列表,而不是使用不同的名称,然后将 applink 扩展到包括新列表(或使用+=)。

代码-

applink = []
while i<len(symbolslist):

    url = "http://www.indeed.com/resumes/-/in-Singapore?co=SG&start="+str(symbolslist[i])
    htmlfile = urllib.urlopen(url)
    htmltext = htmlfile.read()
    regex = '<a target="_blank" href="(.+?)" rel="nofollow"'
    pattern = re.compile(regex)
    tempapplink = re.findall(pattern,htmltext)
    print tempapplink
    applink += tempapplink
    i+=1

【讨论】:

    猜你喜欢
    • 2020-05-05
    • 2023-03-21
    • 2017-12-15
    • 1970-01-01
    • 1970-01-01
    • 2012-04-10
    • 2020-03-04
    • 2021-02-06
    • 1970-01-01
    相关资源
    最近更新 更多