簡體   English   中英

Python:如何在不使用任何預建函數的情況下將列表中的所有項目相乘?

[英]Python: How may I multiply all items in a list without using any prebuilt function?

我知道我應該使用for循環,但是我不知道具體如何。

def product_list(list):
    for item in list:

我已經搜索過有關isse的信息,但發現包含map()和lambda的回復。 我該如何循環?

使用一個臨時變量,並將每個項目乘以它:

def product_list(my_list):  # Don't use `list` as variable name
    product = 1
    for item in my_list:
        product *= item
    return product

更好的方法是將reduce()operator.mul

import operator

def product_list(my_list):
    return reduce(operator.mul, my_list, 1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM