如何将此python打印函数的每一行写入字符串列表?

时间:2011-08-23 21:35:44

标签: python string string-concatenation

我有......

>>> 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)

...而我想要的是将这些行中的小字符串和整数连接成单个字符串,并将其附加到一个列表中,该列表将包含大约1100个元素,每个元素都是文件的名称。我该如何修改循环?

3 个答案:

答案 0 :(得分:4)

ITYM

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

或更短,

l = ['./%02d/IMG%04d.jpg' % (i, j) for i in range(11) for j in range(103)]

答案 1 :(得分:3)

['./%02d/IMG%04d.jpg' % (i, j) for i in range(11) for j in xrange(103)]

答案 2 :(得分:3)

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

或稍微(~6%)更快但更混淆

 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