python - 如何使用 Python 添加数组
问题描述
给定一个使用 Python 3 的数组a = [1,2,3,[4,5]]
,如何添加数组中的所有元素?
sum(a[0])
sun(a[0][1])
上面的代码不起作用。同样在这种情况下,如果给定一个数组,其中数组中的数组数量未知,那么如何计算这些数字?
解决方案
def xsum(x):
if not x:
return 0
head, *tail = x
if isinstance(head, list):
return xsum(head) + xsum(tail)
elif tail:
return head + xsum(tail)
else:
return head
推荐阅读
- c# - DataTable 内存大小的内存分析
- c++ - 构建 3dsmax 插件时如何导入和应用 qss 文件
- docker - 延迟 Gunicorn 直到 Flask 完全加载?
- php - 如何根据密钥可用性将所有输入值分配到数组中而不会发生冲突?
- google-cloud-platform - 获取 GKE 工作负载状态
- microsoft-teams - Micorsoft 团队是否需要特殊配置来改善速率限制问题?
- batch-file - 如何将批处理程序中的变量设置到文本文件的第一行并在批处理文件具有更新的变量时覆盖该行
- scala - if else中如何匹配多个条件
- arrays - 在大型数据集上有效地替换 numpy 中二维数组的许多子数组
- reactjs - AWS Lambda 事件结构在 React 应用程序中使用 Axios 从 API Gateway 获取完整请求