如何在Python3.5+;中向命名的元组添加uuu格式;?
我正在使用为Python早期版本编写的代码如何在Python3.5+;中向命名的元组添加uuu格式;?,python,string,python-3.x,string-formatting,Python,String,Python 3.x,String Formatting,我正在使用为Python早期版本编写的代码 TensorShape = namedtuple('TensorShape', ['batch_size', 'channels', 'height', 'width']) 稍后,我有以下(节略)代码: 因为out\u shape是一个TensorShape,并且它没有定义\uuuuuu格式方法 所以我把张量形状的定义改为 def format_tensorshape(format_spec): return format("{0} {1}
TensorShape = namedtuple('TensorShape', ['batch_size', 'channels', 'height', 'width'])
稍后,我有以下(节略)代码:
因为out\u shape
是一个TensorShape
,并且它没有定义\uuuuuu格式
方法
所以我把张量形状的定义改为
def format_tensorshape(format_spec):
return format("{0} {1} {2} {3}")
TensorShape = namedtuple('TensorShape', ['batch_size', 'channels', 'height', 'width'])
TensorShape.__format__ = format_tensorshape
但这段代码仍然在下游爆炸,只有一个例外
我做错了什么?你的思路是对的——只需将传递到格式或形状的连接到你的呼叫:
屈服
1 2 3 4
您可以简单地使用基于字符串表示的格式。这在中是可能的!s
转换标志,并且由于字符串知道如何解释格式化规范,因此无需为命名双工
创建自定义的格式化方法:
s.append('{:<20} {:<30} {:>20} {!s:>20}'.format(node.kind, node.name, data_shape,
tuple(out_shape)))
# ^^---- here I added the !s
当应用于元组时,您希望从{:>20}
中得到什么行为?调用tuple(out\u shape)
是不可行的(out\u shape
已经是一个tuple),但是如果您想将其显示为(批量大小、通道、高度、宽度)
,您只需调用str(out\u shape)
。因为这是一个字符串,所以格式化方向应该按预期工作。@larsks如果你使用str(out\u shape),那么你会得到类和方法的名称以及值,而不是(批大小、通道、高度、宽度)。我想是的,str(tuple(…)
)。
import collections
def format_tensorshape(self, format_spec):
return format("{0} {1} {2} {3}".format(*self), format_spec)
TensorShape = collections.namedtuple('TensorShape', ['batch_size', 'channels', 'height', 'width'])
TensorShape.__format__ = format_tensorshape
out_shape = TensorShape(1,2,3,4)
print('{:>20}'.format(out_shape))
1 2 3 4
s.append('{:<20} {:<30} {:>20} {!s:>20}'.format(node.kind, node.name, data_shape,
tuple(out_shape)))
# ^^---- here I added the !s
>>> from collections import namedtuple
>>> TensorShape = namedtuple('TensorShape', ['batch_size', 'channels', 'height', 'width'])
>>> '{!s:>20}'.format(tuple(TensorShape(1,1,1,1)))
' (1, 1, 1, 1)'