11

在 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)
4

6 回答 6

13
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)
于 2010-07-01T21:03:42.160 回答
6

我认为join是 Python 中最相似的特性:

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

print(foo.join(", "))

如您所见,当您在里面有多个项目时,情况会更糟,但如果您有分组功能(无论如何这真的很有用!),我认为您可以让它工作而不会有太多麻烦。就像是:

mystuff = [1, 2, "Foo", 34, 42, "Ni", 12, 14, "Blue"]
print(["%d %d %s" % x for x in group(mystuff, 3)].join("\n"))
于 2010-07-01T20:57:01.913 回答
4

对于初学者,我会在 2.6+ 中使用更新的字符串格式化方法

print "{0} {1} {2}".format(*mystuff[x:x+3])
于 2010-07-01T20:54:42.953 回答
3

我想说最 Pythonic 是让列表更深:

mystuff = [(1, 2, "Foo"), (34, 42, "Ni"), (12, 14, "Blue")]
for triplet in mystuff:
    print "%d %d %s" % triplet
于 2010-07-02T01:44:51.883 回答
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)

很好理解,我觉得

于 2013-08-21T02:36:08.810 回答
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))
于 2013-08-21T01:58:22.060 回答