开发者

Iterative printing over two data types in Python

开发者 https://www.devze.com 2023-02-01 06:58 出处:网络
I often browse freely-available art on the web. Actually, I can\'t think of a better use for the internet than to turn it into a gigantic art gallery. When I encounter a set of pieces I quite like, I

I often browse freely-available art on the web. Actually, I can't think of a better use for the internet than to turn it into a gigantic art gallery. When I encounter a set of pieces I quite like, I download them all to my hard drive. wget makes that easy, especially in combination with Python's print function, and I use this all the time to make a list of URLs that I then wget. Say I need to download a list of jpegs that run from art0 to art100 in the directory 'art,' I just tell python

for i in range(0,101):
    print "http://somegallery/somedirectory/art", i

So, this is probably a fairly simple operation in Python, and after a find-and-replace to remove whitespace, it's just a matter of using wget -i, but in days before I knew any Python I'd slavishly right-click and save.

Now I've got a bunch of files from Fredericks & Freiser gallery in New York that all go a(1-14), b(1-14), c(1-14), etc., up to the letter g. I could do that in 7 goes, and it would take me less time than it took to write this SO question.

That said, I want to deepen my knowledge of Python. So, given the letters a-g, how do I print a m开发者_C百科apping of each letter to the integers 1-14?


for i in ['a','b','c','d','e','f','g']:
    for j in range(1,15):
        url = BASE_URL + i + str(j)
        print url

Is that what you are looking for?


Try this:

['{0}{1}'.format(letter, number + 1) for letter in 'abcdefg'
                                     for number in range(14)]


['http://somegallery/somedirectory/art/%s%s\n' % (chr(ordinal), number) for ordinal in range(ord('a'), ord('g')+1) for number in range(1, 15)]


You actually do not need Python for this. Assuming you use bash as your shell (similar mechanisms exist in other shells), you can use brace expansion:

wget http://somegallery/somedirectory/art{a..g}{1..15}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号