Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python List Comprehensions - Join with For loop

I am trying to generate URLs as follows:

http://ergast.com/api/f1/2000/qualifying?limit=10000

I am using Python to generate URLs for the years 2000 to 2015, and to that end, wrote this code snippet:

url = "http://ergast.com/api/f1/"
year = url.join([str(i) + "/qualifying?limit=10000" + "\n" for i in range(1999, 2016)])
print(year)

The output is:

1999/qualifying?limit=10000
http://ergast.com/api/f1/2000/qualifying?limit=10000
http://ergast.com/api/f1/2001/qualifying?limit=10000
http://ergast.com/api/f1/2002/qualifying?limit=10000
http://ergast.com/api/f1/2003/qualifying?limit=10000
http://ergast.com/api/f1/2004/qualifying?limit=10000
......
http://ergast.com/api/f1/2012/qualifying?limit=10000
http://ergast.com/api/f1/2013/qualifying?limit=10000
http://ergast.com/api/f1/2014/qualifying?limit=10000
http://ergast.com/api/f1/2015/qualifying?limit=10000

How do I get rid of the first line? I tried making the range (2000, 2016), but the same thing happened with the first line being 2000 instead of 1999. What am I doing wrong? How can I fix this?

like image 305
CodingInCircles Avatar asked Apr 12 '26 00:04

CodingInCircles


2 Answers

You can use string formatting for this:

url = 'http://ergast.com/api/f1/{0}/qualifying?limit=10000'

print('\n'.join(url.format(year) for year in range(2000, 2016)))

# http://ergast.com/api/f1/2000/qualifying?limit=10000
# http://ergast.com/api/f1/2001/qualifying?limit=10000
# ...
# http://ergast.com/api/f1/2015/qualifying?limit=10000

UPDATE:

Based on OP's comments to pass these urls in requests.get:

url_tpl = 'http://ergast.com/api/f1/{0}/qualifying?limit=10000'

# use list coprehension to get all the urls
all_urls = [url_tpl.format(year) for year in range(2000, 2016)]

for url in all_urls:
    response = requests.get(url)
like image 117
AKS Avatar answered Apr 17 '26 02:04

AKS


Instead of using the URL to join the string, use a list comprehension to create the different URLs.

>>> ["http://ergast.com/api/f1/%d/qualifying?limit=10000" % i for i in range(1999, 2016)]
['http://ergast.com/api/f1/1999/qualifying?limit=10000',
 'http://ergast.com/api/f1/2000/qualifying?limit=10000',
 ...
 'http://ergast.com/api/f1/2014/qualifying?limit=10000',
 'http://ergast.com/api/f1/2015/qualifying?limit=10000']

You could then still use '\n'.join(...) to join all those to one big string, it you like.

like image 27
tobias_k Avatar answered Apr 17 '26 03:04

tobias_k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!