Iterate a format string over a list(在列表上迭代格式字符串)
问题描述
在 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)
这篇关于在列表上迭代格式字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在列表上迭代格式字符串
基础教程推荐
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 包装空间模型 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
