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

1 投票
1 回答
614 浏览
提问于 2025-04-18 18:53

这段代码的目的是把一个函数里的列表传到另一个函数里。这个列表里只会有一个元素。我是Python初学者,需要一些帮助。代码是能运行的,但它只从创建列表的地方带出了一个元素。

当我运行这段代码时,我使用的数字是 high = 100low = 20multi = 15。我希望我的列表里有 [90, 75, 60, 45, 30]。应该有5个元素从 show_mulitples 函数输出成一个列表。我需要把这个列表传到 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()  

1 个回答

2

在你上面的代码中,你是在添加第一个元素后就直接返回这个列表。你需要把返回的那部分代码放到循环外面去(注意:在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

撰写回答