[英]For Loop List Python for Variable URL
So if I wanted to print the contents of a url page or just cycle through many and only change a few segments of the URL how might I do so.因此,如果我想打印 url 页面的内容,或者只是循环浏览多个 URL 并且只更改 URL 的几个部分,我该怎么做。 Given the following:
鉴于以下情况:
If I know the format will usually be the following for any player, minus a few tweeks to the ID and last portion: Format below:如果我知道任何玩家的格式通常如下,ID 和最后一部分减去几个星期:格式如下:
http://espn.go.com/mlb/player/_/id/31000/brad-brach
Lets say I know each players ID and name:假设我知道每个玩家的 ID 和姓名:
PLAYER_NAME = ['brad-brach','oliver-drake',...]
PLAYER_ID = ['31000','31615',...]
for i in PLAYER_ID:
url = 'http://espn.go.com/mlb/player/_/id/'+PLAYER_ID[i]+/'+PLAYER_NAME[i]
Do what ever given that we know all these players in the PLAYER_ID and PLAYER_NAME.只要我们知道 PLAYER_ID 和 PLAYER_NAME 中的所有这些球员,就尽我们所能。
How might I iterate through all the PLAYER_ID's and PLAYER_NAME's without getting a我如何遍历所有 PLAYER_ID 和 PLAYER_NAME 而没有得到
TypeError: list indices must be integers, not str
类型错误:列表索引必须是整数,而不是 str
I know that url is a list and the contents within it PLAYER_ID[0] would be a string.我知道 url 是一个列表,其中的内容 PLAYER_ID[0] 将是一个字符串。 What am I missing here?
我在这里缺少什么?
Select an item from list by index not the string of another list, PLAYER_NAME['31000']?!按索引从列表中选择一个项目而不是另一个列表的字符串,PLAYER_NAME['31000']?!
PLAYER_NAME = ['brad-brach','oliver-drake',...]
PLAYER_ID = ['31000','31615',...]
for i in xrange(len(PLAYER_NAME)):
url = 'http://espn.go.com/mlb/player/_/id/{}/{}'.format(PLAYER_ID[i], PLAYER_NAME[i])
And for an even more elegant solution use zip, thanks to @Pynchia ;)对于更优雅的解决方案,请使用 zip,感谢@Pynchia ;)
PLAYER_NAME = ['brad-brach','oliver-drake',...]
PLAYER_ID = ['31000','31615',...]
URL_PATTERN = 'http://espn.go.com/mlb/player/_/id/{}/{}'
for p_name, p_id in zip(PLAYER_NAME, PLAYER_ID):
url = URL_PATTERN.format(p_id, p_name)
for something in container
will give you each item in the container; for something in container
会给你for something in container
每件物品; this is a very clean way of iterating:这是一种非常干净的迭代方式:
>>> for i in PLAYER_ID:
... print i
31000
31615
When you use PLAYER_ID[i]
, what you really want is the index.当您使用
PLAYER_ID[i]
,您真正想要的是索引。 You can get that by enumerating every element in the list:您可以通过枚举列表中的每个元素来获得它:
>>> for i, element in enumerate(PLAYER_ID):
... print i, element
0 31000
1 31615
However, you don't really need the index, as you already have a clean way of getting the player's ID.但是,您实际上并不需要索引,因为您已经有了一种获取玩家 ID 的简洁方法。
As I mentioned in a comment, better names would be PLAYER_IDS
and PLAYER_NAMES
, so that:正如我在评论中提到的,更好的名字是
PLAYER_IDS
和PLAYER_NAMES
,这样:
>>> for PLAYER_NAME, PLAYER_ID in zip(PLAYER_NAMES, PLAYER_IDS):
... print PLAYER_NAME, PLAYER_ID
brad-brach 31000
oliver-drake 31615
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.