简体   繁体   中英

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. 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:

http://espn.go.com/mlb/player/_/id/31000/brad-brach

Lets say I know each players ID and name:

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.

How might I iterate through all the PLAYER_ID's and PLAYER_NAME's without getting a

TypeError: list indices must be integers, not str

I know that url is a list and the contents within it PLAYER_ID[0] would be a string. What am I missing here?

Select an item from list by index not the string of another list, 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 ;)

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; 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. 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.

As I mentioned in a comment, better names would be PLAYER_IDS and PLAYER_NAMES , so that:

>>> for PLAYER_NAME, PLAYER_ID in zip(PLAYER_NAMES, PLAYER_IDS):
...     print PLAYER_NAME, PLAYER_ID
brad-brach 31000
oliver-drake 31615

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM