在列表上迭代格式字符串
在 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)
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)
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?
Well, unless someone later provides a better example, I think gnibbler's solution is the nicest\closest, 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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
或者使用
.format
如果格式字符串没有硬编码,您可以解析它以计算出每行有多少个术语
将它们放在一起给出
Or using
.format
If the format string is not hardcoded, you can parse it to work out how many terms per line
Putting it all together gives
我认为
join
是 Python 中最相似的功能:正如你所见,当你里面有多个项目时,情况会更糟,尽管如果你有一个 group-by 函数(无论如何,这确实很有用!),我认为你可以使它的工作没有太多麻烦。像这样的东西:
I think
join
is the most similar feature in Python:It's a little worse when you have multiple items inside, as you see, though if you have a group-by function (which is really useful anyway!), I think you can make it work without too much trouble. Something like:
对于初学者,我会使用 2.6+ 中较新的字符串格式化方法
For starters, I'd use the newer string formatting methods in 2.6+
我想说,最 Pythonic 的做法是让列表变得更深:
I'd say the most Pythonic would be to make the list deeper:
我觉得非常好理解
Very understandable, I think
基于赖特的两班轮:
A two liner based on Wright: