python計算列表元素與乘積詳情
更新時間:2022年08月04日 14:10:00 作者:Python熱愛者
這篇文章主要介紹了python計算列表元素與乘積,文章圍繞主題展開詳細內容介紹,具有一定的參考價值,需要的小伙伴可以參考一下
插入代碼塊
使用sum函數(shù):
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(sum(numbers))
使用reduce函數(shù):
# 方式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循環(huán):
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循環(huán):
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] result = 1 for number in numbers: result *= number print(result)
使用reduce函數(shù):
# 方式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)
使用遞歸函數(shù):
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計算列表內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
ruff check文件目錄檢測--exclude參數(shù)設置路徑詳解
這篇文章主要為大家介紹了ruff check文件目錄檢測exclude參數(shù)如何設置多少路徑詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-10-10TensorFlow入門使用 tf.train.Saver()保存模型
這篇文章主要介紹了TensorFlow入門使用 tf.train.Saver()保存模型,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-04-04Pytorch?PyG實現(xiàn)EdgePool圖分類
這篇文章主要為大家介紹了Pytorch?PyG實現(xiàn)EdgePool圖分類示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-04-04