简体   繁体   English

如何在 Python 函数中使用整个列表作为参数?

[英]How to use a whole list as a parameter in a Python function?

I was trying to make a function in Python that would take a list as input, and return a multiple of all the numbers in the list:我试图在 Python 中创建一个函数,它将列表作为输入,并返回列表中所有数字的倍数:

def multiply_list(numbers):
    product = 1

    for int in numbers:
        product = product*numbers[int]

    return product

I tried testing it by using:我尝试使用以下方法对其进行测试:

ints = [1, 7, 3, 4]

print(multiply_list(ints))

However, I get a "list index out of range"-exception.但是,我收到“列表索引超出范围”异常。 For some reason I can't figure out why I am getting this exception.出于某种原因,我无法弄清楚为什么我会收到此异常。 Any advice would be appreciated!任何意见,将不胜感激!

for int in numbers:
        product = product*int

int is the actual item, not an index int 是实际项目,而不是索引

Try this:尝试这个:

def multiply_list(numbers):
  product = 1    
  return [ product * x for x in numbers]

ints = [1, 7, 3, 4]

print(multiply_list(ints))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM