我有......
>>> 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个元素,每个元素都是文件的名称。我该如何修改循环?
答案 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