无法弄清楚如何在Python中修改函数中的列表项?

时间:2017-09-30 22:01:51

标签: python

当我打电话给show_magicians时,会打印出他们的名字,但是我想,当我打电话给make_great时,他们的名字会被添加。

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)

2 个答案:

答案 0 :(得分:1)

请注意,magician_names中的for name不允许您更改名称的列表值,因为Python中的字符串无法就地更改,您必须用新值替换它们。您必须使用magician_names [0] ...等直接编辑列表。这里我返回了一个包含更改名称的新列表,这是处理传递给方法的列表的首选方法。

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)

这是一种直接更改列表的方法:

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'

答案 1 :(得分:0)

#!/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)