首页 > 解决方案 > 两行列表元素的阶乘

问题描述

我在这里有这段代码,它为我们提供了每个参数的阶乘

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

但我遇到了问题,因为加入只处理字符串而不是数字任何人都有其他解决方案或可以修复我的代码。

标签: pythonfunctionlambdalist-comprehensionfactorial

解决方案


.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)), [6, 7])))

但是,我认为这不会产生您想要的输出。

尝试这个:

print("\n".join(map(lambda f: "fac of {} is {}".format(f, math.factorial(f)), [6, 7])))

这个输出更好,并且:

  • 不需要所有调用,str因为.format在插值时转换为字符串。

  • 无需多次指定数字

  • 当我们将数字添加到传递给的数组时,输出会动态增长map


推荐阅读