Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python3.5+;中向命名的元组添加uuu格式;?_Python_String_Python 3.x_String Formatting - Fatal编程技术网

如何在Python3.5+;中向命名的元组添加uuu格式;?

如何在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}

我正在使用为Python早期版本编写的代码

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)'