问题描述
def fac(*x):
for a in range(len(x)):
r = 1
for i in range(list(x).pop(a)):
r+= r * i
print("fac of ",x[a],"is :",r)
fac(6,7)
,我只想两行 所以我尝试了这段代码:
import math
print("fac of "+str(6)+" is "+"\nfac of "+str(7)+" is \n".join( list(map(lambda f:math.factorial(f),[6,7]))))
但是我有问题,因为join只处理字符串而不处理数字 任何人都有其他解决方案或可以修复我的代码。
解决方法
.join
仅适用于字符串序列,因此您需要使lambda
内的map
返回一个字符串。
使用str
:
... map(lambda f: str(math.factorial(f)),[6,7])
作为旁注,您不需要list(...)
,因为join
会很高兴地对任何可迭代的对象进行迭代:
print("fac of " + str(6) + " is " + "\nfac of " + str(7) + " is \n".join(map(lambda f: str(math.factorial(f)),7])))
但是,我认为这不会产生您想要的输出。
尝试一下:
print("\n".join(map(lambda f: "fac of {} is {}".format(f,math.factorial(f)),7])))
此输出更好,并且:
-
不需要所有对
str
的调用,因为.format
在插值时会转换为字符串。 -
无需多次指定数字
-
在将数字添加到传递给
的数组中时,输出会动态增长map