如何循环存储在 url 列表中的值?

How to loop the values stored in a list in a url?

i = ['Link_1/','Link_2/','Link_3/']

my_url ='http://www.example.com/category/{}'.format(i)

我正在尝试创建一个循环,以便来自 i 的所有值都可以是 there.But我被困在我需要进一步做的事情上。

Python 对此有列表理解:

links = ['Link_1/','Link_2/', 'Link_3']
my_urls = ['http://www.example.com/category/{}'.format(url) for url in links]

根据您想对每个 URL 执行的操作,您将需要使用显式循环(如 for or while), or a list comprehension.

如果您只想获取格式化字符串的列表,最简单的方法是使用列表理解:

my_urls = ['http://www.example.com/category/{}'.format(link) for link in i]

请注意,我将 .../{}'format.(url)' 更改为 .../{}'.format(url)'。点 separates the object from it's method. In this case, the object is the string 'http://www.example.com/category/{}'. That string has a format 方法,您可以通过 string.format(...).

访问它

如果您想对列表 i 的每个元素进行更高级的处理,而不仅仅是格式化链接,您可以使用 for 循环:

for link in i:
    my_url = 'http://www.example.com/category/{}'.format(link)
    # Do what you need to do to `my_url` before you move on to the next link

请花点时间阅读我发布到官方 Python 文档的链接。它可能会帮助您将来自己解决类似的问题。