如何将这个 python print 函数的每一行写入字符串列表?

发布于 2024-12-01 02:22:15 字数 350 浏览 0 评论 0原文

我有...

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

你列表最软的妹 2024-12-08 02:22:15

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

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)]
酒几许 2024-12-08 02:22:15
['./%02d/IMG%04d.jpg' % (i, j) for i in range(11) for j in xrange(103)]
['./%02d/IMG%04d.jpg' % (i, j) for i in range(11) for j in xrange(103)]
公布 2024-12-08 02:22:15
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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文