在python中从一个函数到另一个函数传递列表

2024-04-16 10:10:44 发布

您现在位置:Python中文网/ 问答频道 /正文

此代码应该将列表从一个函数带到另一个函数。列表将只包含一个元素。我是Python的初学者,需要一些帮助。代码可以工作,但只从创建列表的位置引入一个元素。你知道吗

当我输出代码时,我一直使用数字high = 100low = 20multi = 15。我的清单上应该有[90, 75, 60, 45, 30]show_mulitples函数中应该有5个元素作为一个列表。我需要把这个列表放到show_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()  

Tags: the函数代码元素列表fordefshow
1条回答
网友
1楼 · 发布于 2024-04-16 10:10:44

在上面的代码中,您将在第一个元素添加到列表之后直接返回该列表。您需要将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

相关问题 更多 >