python for循环及其生成器问题

时间:2019-01-30 18:32:11

标签: python string for-loop

我正在尝试生成一些链接。

注意:退货与打印存在问题。

当我用return编写代码时,它只返回一字:

运行此代码:

import requests
import re

wikiurl = 'https://en.wikipedia.org/wiki/List_of_states_and_territories_of_the_United_States'


state_pat = re.compile(r'title=\"(\w+)\">')

def get_page_content(url):
    response = requests.get(url)
    return response.text

def link_generator(wikiurl):
    content = get_page_content(wikiurl)
    names = state_pat.findall(content)
    for i in names:
        return 'https://www.local.com/business/results/listing.cfm?s=tile+and+grout+cleaning&ar=' + i + '%2CNY&gsp=ZFZWU1RaU09zWGNYdjFEV1l2ZHFLNVZUUFRPT3c3a21lbFVCbERQOU5VS3p6ai9DRXNMa29PcVZ0ZVV0TXZLM01wUVFUUHZYK2lrMnB5VGJyMHZJeUNoK1dXaUoxZ1NKT3AxbVlJOGN1aVBEb1NRMzlCemdDVHh5aGd3eU5DYUpKWDRtNFVQR0llOFJibUhQR3pSV3ppWFR4ekJoRVltL29UdFQ0MW9KUS9IenJrcjVBMUt3bkErRnlSVnFjRnZ0TjhRWEdET0FuZWRVUGNkemdxUlkzOUYyUjZXbHBzQWRMY3hEUTY4WmtnYkRsSkEvazBrVVY5d0NmSVVMaWp0WnNDNmFsZFNzMitWeHZDYTg2YmJwRGQzSisvOUJaYWNBaFdUd21LaWJpNk9veS9OT1N1VE5DV3RUNDIxdkY5NmZ4bWFVcWtLc1BlVkNRNlEvSG4ydER1T1ZkcXk4Um5BWU5kUU9UZnVOUE9BPQ%253D%253D&lwfilter=&wsrt=&wpn='


a = link_generator(wikiurl)
print(a)

如果我运行此代码,将打印内容添加到功能中,它将返回所有链接,为什么?我需要所有带有return

的链接

运行此代码:您将看到不同的内容:

import requests
import re

wikiurl = 'https://en.wikipedia.org/wiki/List_of_states_and_territories_of_the_United_States'


state_pat = re.compile(r'title=\"(\w+)\">')

def get_page_content(url):
    response = requests.get(url)
    return response.text

def link_generator(wikiurl):
    content = get_page_content(wikiurl)
    names = state_pat.findall(content)
    for i in names:
        print('https://www.local.com/business/results/listing.cfm?s=tile+and+grout+cleaning&ar=' + i + '%2CNY&gsp=ZFZWU1RaU09zWGNYdjFEV1l2ZHFLNVZUUFRPT3c3a21lbFVCbERQOU5VS3p6ai9DRXNMa29PcVZ0ZVV0TXZLM01wUVFUUHZYK2lrMnB5VGJyMHZJeUNoK1dXaUoxZ1NKT3AxbVlJOGN1aVBEb1NRMzlCemdDVHh5aGd3eU5DYUpKWDRtNFVQR0llOFJibUhQR3pSV3ppWFR4ekJoRVltL29UdFQ0MW9KUS9IenJrcjVBMUt3bkErRnlSVnFjRnZ0TjhRWEdET0FuZWRVUGNkemdxUlkzOUYyUjZXbHBzQWRMY3hEUTY4WmtnYkRsSkEvazBrVVY5d0NmSVVMaWp0WnNDNmFsZFNzMitWeHZDYTg2YmJwRGQzSisvOUJaYWNBaFdUd21LaWJpNk9veS9OT1N1VE5DV3RUNDIxdkY5NmZ4bWFVcWtLc1BlVkNRNlEvSG4ydER1T1ZkcXk4Um5BWU5kUU9UZnVOUE9BPQ%253D%253D&lwfilter=&wsrt=&wpn=')


a = link_generator(wikiurl)
print(a)

1 个答案:

答案 0 :(得分:2)

在函数中发出return语句时,它不会执行任何其他行,并返回到其调用方。如果要迭代地返回生成器中的项目,可以将return替换为yield。或者,将结果收集为列表,然后返回列表。

然后,当您调用以下命令时,您需要更改最后一行:

a = list(link_generator(wikiurl))

打开发电机包装