在python中从函数到函数传递列表
这段代码应该将列表从一个函数带到另一个函数。列表将只包含一个元素。我是Python初学者,需要一些帮助。代码可以工作,但只从创建列表的位置引入一个元素 当我输出代码时,我一直在使用数字在python中从函数到函数传递列表,python,python-3.x,Python,Python 3.x,这段代码应该将列表从一个函数带到另一个函数。列表将只包含一个元素。我是Python初学者,需要一些帮助。代码可以工作,但只从创建列表的位置引入一个元素 当我输出代码时,我一直在使用数字high=100、low=20和multi=15。我的列表中应该有[90,75,60,45,30]。show\u mulitples函数作为一个列表应该有5个元素。我需要将该列表放入show\u list函数中,然后计算元素,显示倍数,并获得平均值。但我得到的只是第一个元素,90 def main(): #
high=100
、low=20
和multi=15
。我的列表中应该有[90,75,60,45,30]
。show\u mulitples
函数作为一个列表应该有5个元素。我需要将该列表放入show\u list
函数中,然后计算元素,显示倍数,并获得平均值。但我得到的只是第一个元素,90
def main():
#get the integers
high = int(input('Enter the high integer for the range '))
low = int(input('Enter the low integer for the range '))
multi = int(input('Enter the integer for the multiples '))
#call the function
multiples = show_multiples(low, high, multi)
list_info = show_list(multiples)
#take the arguments into the function
def show_multiples(low, high, multi):
#make empty list
multi_list = []
#make the list
for i in range(high, low, -1):
if i % multi == 0:
multi_list.append(i)
print('List was created')
return multi_list
#take the list into the function
def show_list(multiples):
#create empty total
total = 0.0
#add the list together
for value in multiples:
total += value
#get Average
avg = total / len(multiples)
print('This list has',len(multiples),'elements')
print(multiples)
print('The average of the multiples is',avg)
main()
在上面的代码中,在将第一个元素添加到列表后,您将直接返回该列表。您需要将return语句移出循环(注意:在Python中,缩进很重要!) 尝试以下方法:
def show_multiples(low, high, multi):
#make empty list
multi_list = []
#make the list
for i in range(high, low, -1):
if i % multi == 0:
multi_list.append(i)
print('List was created')
return multi_list # <-- this should be out of the loop
def显示倍数(低、高、多):
#空名单
多线程列表=[]
#上榜
对于范围内的i(高、低、-1):
如果i%multi==0:
多重列表追加(i)
打印('已创建列表')
return multi_list#我试过了,它在列表中返回为零。@chukchukk您检查过输入变量中的内容了吗?这个函数对我来说很好,就是这样!非常感谢你。我刚开始学习Python。我不得不一路回到for循环。现在成功了。@chukchukk不用担心,很高兴现在成功了!你介意将我的答案标记为已接受吗:)?我对这里的帖子是全新的,尽管过去两年来我一直在看这里的问题来帮助我。我只是想确定我做得对。单击答案旁边的箭头?