在列表中迭代格式字符串 [英] Iterate a format string over a list

查看:149
本文介绍了在列表中迭代格式字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Lisp中,你可以这样:

 (setf my-stuff'(1 2Foo34 42Ni12 14Blue))
(format t〜{〜d〜r〜s〜%〜}my-stuff)

在同一个列表上循环迭代的方式是什么?首先想到的是:

$ $ $ $ $ $ c $ mystuff = 1,2,Foo 34,42 Ni (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] 
(* [iter(mystuff)] * 3):
print格式(* x)


解决方案 $ zip $($ p code $ c $ mystuff = [1,2, * [iter(mystuff)] * 3):
print%d $%$%$
$ c $ $ b

或使用 .format

  mystuff = [1 ,2,Foo,34,42,Ni,12,14,Blue] 
(* [iter(mystuff)] * 3):
print格式字符串(* x)

如果格式字符串不是硬编码,你可以解析它,以确定每行多少条款

 从条款g import formatter 
num_terms = sum(1 for 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 zip(* [iter(mystuff)] * num_terms):
print fmt.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)

解决方案

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

Or using .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}"))

Putting it all together gives

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)

这篇关于在列表中迭代格式字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆