开发者

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 lis开发者_StackOverflow中文版t 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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜