简体   繁体   中英

Can't figure out how to modify list items in function in Python?

When I call show_magicians, their names are printed, but I want, when I call make_great, have their name + the Great added.

def make_great(magician_names):
    """Adds the phrase 'the Great' to each magician's name."""
    for name in magician_names:
        # I want to add 'the Great' to each item in the list
        # magician_names so that when I call show_magicians, 
        # the items in the list will have 'the Great' added 
        # to them.

def show_magicians(magician_names):
    """Print the names of magicians in a list."""
    for name in magician_names:
        print(name.title())

magician_names = ['peter', 'maria', 'joshua']
show_magicians(magician_names)
make_great(magician_names)
show_magicians(magician_names)

Note the for name in magician_names won't allow you to change the list value of the name as strings in Python can't be changed in place, you must replace them with a new value. You'll have to edit the list directly by using magician_names[0]... etc. Here I have returned a new list with the changed names, which is the prefered way to deal with lists passed to methods.

def make_great(magician_names):
    """Adds the phrase 'the Great' to each magician's name."""
    return [ name + ' the Great' for name in magician_names]


def show_magicians(magician_names):
    """Print the names of magicians in a list."""
    for name in magician_names:
        print(name.title())

magician_names = ['peter', 'maria', 'joshua']
show_magicians(magician_names)
magician_names = make_great(magician_names)
show_magicians(magician_names)

Here is a method that changes the list directly:

def make_great(magician_names):
    """Adds the phrase 'the Great' to each magician's name."""
    for index in range(len(magician_names)):
        magician_names[index] += ' the Great'
#!/usr/bin/python

def make_great(magician_names):
        """Adds the phrase 'the Great' to each magician's name."""
        for name in magician_names:
                print "{} the Great".format(name)

def show_magicians(magician_names):
        """Print the names of magicians in a list."""
        for name in magician_names:
                print(name.title())

magician_names = ['peter', 'maria', 'joshua']
show_magicians(magician_names)
make_great(magician_names)
show_magicians(magician_names)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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