python - 两行列表元素的阶乘
问题描述
我在这里有这段代码,它为我们提供了每个参数的阶乘
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
仅适用于字符串序列,因此您需要使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
推荐阅读
- php - 只有 Codeigniter 回调函数正在工作,其余验证规则被忽略
- sql-server - 本地数据库的 SQL 连接字符串
- angular - 如果我两次单击相同的锚点,使用片段哈希的角度路由将不起作用
- python - 如果嵌套列表包含某个值,则从列表中删除嵌套列表
- javascript - Paperjs - 无法清除光栅
- android-studio - Android Studio 中响应式设计的最佳方式
- c# - 使用 ML.net 时出现“未找到特征列‘特征’”错误
- python - Python - 如何让 2 个对象相互引用?(循环依赖)
- reactjs - react-router-dom 提示从不显示
- r - 尝试使用 iNext() 时出现错误消息(下标数不正确)