def mult(numbers):
return [10] * len(numbers)
number = [1,2,5,6,7,8,10]
mult(number)
我希望输出[10,20,50.......]
但这是我得到的[10, 10, 10, 10, 10, 10, 10]
答案 0 :(得分:1)
这里是您正在做的事情,带有注释:
def mult(numbers):
return [10] * len(numbers)
# [10] --> Take the list [10]
# len(numbers) --> Take the length of the list `numbers`, which has 7 elements
# [10] * len(numbers) --> repeat [10] seven times, to get [10, 10, 10, 10, 10, 10, 10]
我认为问题是您误解了len()
函数的功能以及*
(乘法)运算符如何与列表一起使用。如果要将每个数字乘以10,则应执行以下操作:
def mult(numbers):
multed = [] # create an empty list to store the result
for num in numbers: # iterate through the elements in `numbers` one by one
multed.append(10 * num) # add (10 * element) to our new list
return multed # return the list we've created
Python还具有 list comprehensions ,可以使这段代码更加简洁:
def mult(numbers):
return [10*num for num in numbers]
# this does the same thing as above
答案 1 :(得分:0)
这就是我要做的
def mult(numbers):
return [10*i for i in numbers]
number = [1,2,5,6,7,8,10]
mult(number)
您的方法只是获取值10
并复制等于输入数组len
的次数。
答案 2 :(得分:0)
我认为您应该尝试这种方式。
def mult(number):
return 10 * number
number = [1,2,5,6,7,8,10]
answer = []
for i in number:
answer.append(mult(i))
print(answer)