python计算列表元素与乘积详情
作者:Python热爱者
这篇文章主要介绍了python计算列表元素与乘积,文章围绕主题展开详细内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下
插入代码块
使用sum函数:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(sum(numbers))
使用reduce函数:
# 方式1 from functools import reduce numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] results = reduce(lambda x, y: x + y, numbers) print(results) # 方式2 from operator import add from functools import reduce numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] results = reduce(add, numbers) print(results)
使用for循环:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] result = 0 for number in numbers: result += number print(result)
使用递归:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] def cal(list1, size): if size: return list1[size - 1] + cal(list1, size - 1) return size print(cal(numbers, len(numbers)))
列表乘积计算
使用for循环:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] result = 1 for number in numbers: result *= number print(result)
使用reduce函数:
# 方式1 from functools import reduce numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] results = reduce(lambda x, y: x * y, numbers) print(results) # 方式2 from operator import mul from functools import reduce numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] results = reduce(mul, numbers) print(results)
使用递归函数:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] def cal(list1, size): if size == 0: return 1 return list1[size - 1] * cal(list1, size - 1) print(cal(numbers, len(numbers)))
到此这篇关于python计算列表元素与乘积的文章就介绍到这了,更多相关python计算列表内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!