我正在进行学习Python艰苦的方式练习24,同时将书中使用的所有旧样式格式(%)转换为我喜欢的新样式(.format())。你知道吗
正如您在下面的代码中所看到的,如果我分配一个变量“p”,我就可以成功地解压该函数返回的元组值。但是当我直接使用这个返回值时,它抛出了一个TypeError。你知道吗
def secret_formula(started):
jelly_beans = started * 500
jars = jelly_beans / 1000
crates = jars / 100
return jelly_beans, jars, crates
start_point = 10000
#Old style
print("We'd have %d beans, %d jars, and %d crates." % secret_formula(start_point))
#New style that works
print("We'd have {p[0]:.0f} beans, {p[1]:.0f} jars, and {p[2]:.0f} crates.".format(p=secret_formula(start_point)))
#This doesn't work:
print("We'd have {0:.0f} beans, {1:.0f} jars, and {2:.0f} crates.".format(secret_formula(start_point)))
抛出错误:
Traceback (most recent call last):
File "ex.py", line 16, in <module>
print("We'd have {0:.0f} beans, {1:.0f} jars, and {2:.0f} crates.".format(secret_formula(start_point)))
TypeError: unsupported format string passed to tuple.__format__
将
secret_formula
的返回值按位置传递给format
并不比按关键字传递更直接。无论哪种方式,您都将返回值作为单个参数传递。你知道吗要在作为
p
关键字参数传递时访问该参数的元素,请使用p[0]
、p[1]
和p[2]
。类似地,在按位置传递参数时,必须访问元素0[0]
、0[1]
和0[2]
,指定位置0
。(这是str.format
处理格式占位符的具体方式,而不是普通的Python索引语法):但是,用
*
解包返回值,将元素作为单独的参数传递,将更简单、更常规:这是因为要传递一个由3个值组成的元组作为函数的输出
要实现这一点,需要使用
*
解压元组也可以对对象执行此操作,其中键应与函数参数名称匹配,例如:
相关问题 更多 >
编程相关推荐