使用for循环修改列表中的字符串?

时间:2016-01-19 16:54:27

标签: python

这是我写的代码:

def show_magicians(magicians):
     """prints the names of magicians"""
    for magician in magicians:
        print(magician)

def make_great(magicians):
    """adds the word great to the string"""
    for magician in magicians:
        magician = magician + " the great"

list_of_magicians = ["Omen", "Carla", "David"]

greats = make_great(list_of_magicians)

print(greats)

从终端运行时我从程序中得到的结果是"无"。请告诉我代码的问题。

而不是使用print(greats),使用show_magicians(greats)会给我以下错误:

Traceback (most recent call last):
  File "C:\Users\-myname-\Documents\python_workspace\functions6.py", line 18,    
  in <module>
    show_magicians(greats)
  File "C:\Users\-myname-\Documents\python_workspace\functions6.py", line 5,
  in show_magicians
     for magician in magicians:
 TypeError: 'NoneType' object is not iterable

请给我建议并彻底解释您为修复代码所做的工作。

3 个答案:

答案 0 :(得分:0)

问题是双重的:

magician = magician + " the great"

会将名称魔术师分配给循环体内的新字符串,但不会对字符串执行任何操作。您没有修改正在迭代的列表。

第二个问题是make_great没有返回任何内容,因此默认返回None

以下是修复:

def make_great(magicians):
    return [m + " the great" for m in magicians]

这使用列表理解,另一种写入方式是

def make_great(magicians):
    result = []
    for m in magicians:
        result.append(m + " the great")
    return result

请注意,我们实际上正在使用我们创建的新字符串执行某些操作,并且在两种情况下都会返回结果。

答案 1 :(得分:0)

两个问题:

  1. 您只是更改字符串的副本(for循环创建列表中每个元素的副本)。

  2. 您的功能没有返回任何内容

  3. 你需要做这样的事情(就地修改):

    auth.uid

    或者像这样(返回副本):

    def show_magicians(magicians):
        for magician in magicians:
            print(magician)
    
    def make_great(magicians):
        for i in range(len(magicians)):
            magicians[i] += " the great"
    
    list_of_magicians = ["Omen", "Carla", "David"]
    
    make_great(list_of_magicians)
    
    print(list_of_magicians)
    

答案 2 :(得分:0)

看起来你需要在make_great方法中实例化另一个数组,并return新数组。

def make_great(magicians):
    """adds the word great to the string"""
    great_magicians = []
    for magician in magicians:
        magician = magician + " the great"
        great_magicians.append(magician)
    return great_magicians