在列表上迭代格式字符串
问题描述
在 Lisp 中,你可以有这样的东西:
In Lisp, you can have something like this:
(setf my-stuff '(1 2 "Foo" 34 42 "Ni" 12 14 "Blue"))
(format t "~{~d ~r ~s~%~}" my-stuff)
迭代同一个列表的最 Pythonic 方式是什么?首先想到的是:
What would be the most Pythonic way to iterate over that same list? The first thing that comes to mind is:
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])
但这对我来说感觉很尴尬.我确定有更好的方法吗?
But that just feels awkward to me. I'm sure there's a better way?
好吧,除非有人后来提供了更好的例子,否则我认为 gnibbler 的解决方案是最好的最接近的,尽管起初它的工作方式可能并不那么明显:
Well, unless someone later provides a better example, I think gnibbler's solution is the nicestclosest, though it may not be quite as apparent at first how it does what it does:
mystuff = [1, 2, "Foo", 34, 42, "Ni", 12, 14, "Blue"]
for x in zip(*[iter(mystuff)]*3):
print "{0} {1} {2}".format(*x)
解决方案
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)
如果格式字符串没有硬编码,您可以对其进行解析以计算出每行有多少项
If the format string is not hardcoded, you can parse it to work out how many terms per line
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)
相关文章