在列表上迭代格式字符串

时间:2010-07-01 20:47:56

标签: python formatting iteration language-comparisons

在Lisp中,你可以这样:

(setf my-stuff '(1 2 "Foo" 34 42 "Ni" 12 14 "Blue"))
(format t "~{~d ~r ~s~%~}" my-stuff)

迭代同一个列表的最Pythonic方法是什么?首先想到的是:

mystuff = [1, 2, "Foo", 34, 42, "Ni", 12, 14, "Blue"]
for x in xrange(0, len(mystuff)-1, 3):
    print "%d %d %s" % tuple(mystuff[x:x+3])

但这对我来说感觉很尴尬。我确定有更好的方法吗?


好吧,除非有人后来提供了一个更好的例子,我认为gnibbler的解决方案是最好的\最接近的,虽然它起初可能不那么明显它的作用:

mystuff = [1, 2, "Foo", 34, 42, "Ni", 12, 14, "Blue"]
for x in zip(*[iter(mystuff)]*3):
    print "{0} {1} {2}".format(*x)

6 个答案:

答案 0 :(得分:12)

mystuff = [1, 2, "Foo", 34, 42, "Ni", 12, 14, "Blue"]
for x in zip(*[iter(mystuff)]*3):
    print "%d %d %s"%x

或使用.format

mystuff = [1, 2, "Foo", 34, 42, "Ni", 12, 14, "Blue"]
for x in zip(*[iter(mystuff)]*3):
    print "{0} {1} {2}".format(*x)

如果格式字符串没有硬编码,您可以解析它以计算每行的条件数

from string import Formatter
num_terms = sum(1 for x in Formatter().parse("{0} {1} {2}"))

将所有内容放在一起会产生

mystuff = [1, 2, "Foo", 34, 42, "Ni", 12, 14, "Blue"]
fmt = "{0} {1} {2}"
num_terms = sum(1 for x in Formatter().parse(fmt))
for x in zip(*[iter(mystuff)]*num_terms):
    print fmt.format(*x)

答案 1 :(得分:4)

对于初学者,我会在2.6 +

中使用较新的字符串格式化方法
print "{0} {1} {2}".format(*mystuff[x:x+3])

答案 2 :(得分:4)

我认为join是Python中最相似的功能:

(format t "~{~D, ~}" foo)

print(foo.join(", "))

如你所见,当你有多个项目时,情况会更糟,但如果你有一个group-by功能(这真的很有用!),我认为你可以毫无困难地使它工作。类似的东西:

mystuff = [1, 2, "Foo", 34, 42, "Ni", 12, 14, "Blue"]
print(["%d %d %s" % x for x in group(mystuff, 3)].join("\n"))

答案 3 :(得分:3)

我认为Pythonic最多的是让名单更深入:

mystuff = [(1, 2, "Foo"), (34, 42, "Ni"), (12, 14, "Blue")]
for triplet in mystuff:
    print "%d %d %s" % triplet

答案 4 :(得分:2)

stuff = [1, 2, "Foo", 34, 42, "Ni", 12, 14, "Blue"]

it = iter(stuff)
itn = it.next

print '\n'.join("%d %d %s" % (el,itn(),itn())
                for el in it)

非常可以理解,我认为

答案 5 :(得分:0)

基于赖特的双人班轮:

mystuff = [1, 2, "Foo", 34, 42, "Ni", 12, 14, "Blue"]
print '\n'.join("{0},{1},{2}".format(*mystuff[x:x+3]) for x in xrange(0, len(mystuff)-1, 3))