简体   繁体   English

将列表的副本传递给python中的函数

[英]Passing copy of a list to a function in python

I'm trying to pass a copy of a list to a function in python so I can pop and append to a new list without losing the information in the old list. 我正在尝试将列表的副本传递给python中的函数,这样我就可以弹出并附加到新列表而不会丢失旧列表中的信息。 But I'm having trouble. 但我遇到了麻烦。

here's my code 这是我的代码

def show_magicians(magicians):
    for magician in magicians:
        print (magician.title())
        return magicians

def make_great(magicians):
    for magician in magicians:
        new_magician = magicians.pop()
        new_magicians.append(new_magician)
        print (new_magician.title() + ", is a great magician!!")
        return magicians

new_magicians = []
magicians = ['merlin', 'blaine', 'agaybi', 'copperfield']   
show_magicians(magicians)
make_great(magicians[:])
print ('\n' , magicians)
print ('\n' , new_magicians)

The second function is supposed to move the elements from the old list to the new and print the simple statement for each one without emptying the old list. 第二个函数应该将元素从旧列表移动到新列表,并为每个元素打印简单语句而不清空旧列表。 The problem is I get only 1 element printed and the same element is the only element moved. 问题是我只打印了1个元素,并且相同的元素是唯一移动的元素。

What am I doing wrong? 我究竟做错了什么?

You are returning after the first magician is processed 在第一位魔术师处理完毕后你就回来了

Change the make_great function as follows 更改make_great函数,如下所示

def make_great(magicians):
    for magician in magicians:
        new_magician = magicians.pop()
        new_magicians.append(new_magician)
        print (new_magician.title() + ", is a great magician!!")
    return magicians

The existing answer solves your immediate problem, but your code is still unnecessarily confusing, which I think contributed to your getting stuck. 现有的答案解决了您当前的问题,但您的代码仍然不必要地混淆,我认为这会导致您遇到困难。

The "correct" way to do this is to avoid mutating magicians within make_great at all. 这样做的“正确”方法是避免在make_great中改变magicians A Python function taking a mutable argument like this should either mutate its argument and return None or create a new object and return that. Python函数采取一个可变的参数是这样要么变异的参数和返回None 创建一个新的对象,并返回。 It should certainly not (for such a trivial task at least) mutate both its argument and an object in the enclosing scope and return that second object. 它当然不应该(至少这样一个微不足道的任务)改变它的参数封闭范围内的对象返回第二个对象。

For example, you could have done: 例如,你可以做到:

def make_great(magicians):
    """Make each magician in the input great."""
    new_magicians = []  # create a brand new list
    for name in magicians:  # iterate over old list
        new_magicians.append(name + ' is a great magician!')  # add to new list
    return new_magicians  # note this is outside the for loop

Then you don't need to create new_magicians outside the function, or pass a copy of the original magicians to it: 然后你不需要在函数外创建new_magicians ,或者将原始magicians的副本传递给它:

magicians = ['merlin', 'blaine', 'agaybi', 'copperfield']   
new_magicians = make_great(magicians)
print(magicians)  # still the same
print(new_magicians)  # brand new list

Ok so first of all thank you all so much. 好的,首先非常感谢你们。 I finally figured out the problem and how to solve it. 我终于找到了问题以及如何解决它。 The exercise I'm working on specifically wants me to use the [:] to make a shallow copy of the list and pass it through a function to create a new list by popping. 我正在进行的练习特别要求我使用[:]制作列表的浅表副本,并通过函数传递它以通过弹出创建新列表。

The problem was I kept the for loop that prints the statement, inside the function instead of placing outside to be global. 问题是我保持for循环打印语句,在函数内部而不是放在外面是全局的。

Here's the new and correct code: 这是新的正确代码:

def show_magicians(magicians):
    for magician in magicians:
        print (magician.title())


def make_great(magicians):
    while magicians:
        new_magician = magicians.pop()
        new_magicians.append(new_magician)


new_magicians = []
magicians = ['merlin', 'blaine', 'agaybi', 'copperfield']
show_magicians(magicians)
make_great(magicians[:])

for magician in magicians:
    print ('\n' + magician.title() + " is a great magician!!")

print ('\n')
print (magicians)
print ('\n')
print (new_magicians)   

Thanks again and sorry for the confusion. 再次感谢,并为此感到抱歉。

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

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