简体   繁体   中英

How can I write each line of this python print function to a list of strings?

I have...

>>> for i in range(11):
...     for j in range(103):
...             print "./", '%02d' % i, "/IMG", '%04d' % j, ".jpg"
...
>>> (prints a whole bunch of lines representing files in a group of directories)

...and what I want instead is to concatenate the little strings and ints in those lines into single strings, and append it to a list which will comprise approximately 1100 elements, each of which is the name of a file. How can I amend the loop?

ITYM

l = []
for i in range(11):
    for j in range(103):
        l.append()

or, shorter,

l = ['./%02d/IMG%04d.jpg' % (i, j) for i in range(11) for j in range(103)]
['./%02d/IMG%04d.jpg' % (i, j) for i in range(11) for j in xrange(103)]
from itertools import product
['./%02d/IMG%04d.jpg'%item for item in product(range(11),range(103))]

or slightly(~6%) faster but more obfuscated

 map('./%02d/IMG%04d.jpg'.__mod__, product(range(11),range(103)))
$ python -m timeit -s"from itertools import product" "['./%02d/IMG%04d.jpg'%item for item in product(range(11),range(103))]"
1000 loops, best of 3: 1.56 msec per loop

$ python -m timeit -s"from itertools import product" "map('./%02d/IMG%04d.jpg'.__mod__, product(range(11),range(103)))"
1000 loops, best of 3: 1.46 msec per loop

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