函数传递列表练习题

用到的知识点:

1、函数可以传递列表

2、函数可以修改列表

3、如果不想用函数修改列表,则可以用function_name(list_name[:]) 创建列表的副本,对列表副本进行操作。

 

不变的魔术师:修改你为完成练习 8-10 而编写的程序,在调用函数make_great()时,向它传递魔术师列表的副本。由于不想修改原始列表,请返回修改后的列表,并将其存储到另一个列表中。分别使用这两个列表来调用 show_magicians(),确认一个列表包含的是原来的魔术师名字,而另一个列表包含的是添加了字样“the Great”的魔术师名字。 

 

 

def show_magicians(names):
    for name in names:
        print(name.title())

def make_great(names):
    for i in range(len(great_names)):
        great_names[i]='The great '+great_names[i]
    return great_names

magicians_names = ['hong tao','xiao weihong','hong yumi','hong yuchan']

great_names=magicians_names[:]

make_great(great_names)

show_magicians(magicians_names)

show_magicians(great_names)

 

下午找了一些资料,觉得上面的写法太low了,于是我定义了三个函数:

第一个函数是纯粹的传递列表,

第二个函数是修改列表内容,

第三个函数是对比,观察创建列表副本和不创建有什么区别

 

def show_magicians(names):
    for name in names:
        print(name.title())


def make_great(names):
    for i in range(len(names)):
        names[i]="The great "+names[i].title()
    return names

def contrast(names):
    print('Before execution :'+str(magicians_names))
    make_great(magicians_names[:])
    print('After execution :' + str(magicians_names))

def contrast2(names):
    print('Before execution :'+str(magicians_names))
    make_great(magicians_names)
    print('After execution :' + str(magicians_names))

magicians_names = ['hong tao','xiao weihong','hong yumi','hong yuchan']

contrast(magicians_names)

contrast2(magicians_names)

 

 

附:网上最有名的关于函数传递列表的教程:

https://blog.csdn.net/sinat_38682860/article/details/88618603

 

def send_invitation(exports,informed):
    while exports:
        export=exports.pop()
        print(export+" 您好,现在邀请您参加会议....")
        informed.append(export)

def print_invitation(exports,informed):
    print('执行前:experts= '+str(exports)+' ,informed= '+str(informed))
    send_invitation(exports[:],informed)
    print('执行后:experts= '+str(exports)+' ,informed= '+str(informed))


exports=['洪韬','肖伟宏','洪语禅','洪语谧']
informed = []

print_invitation(exports,informed)

 

posted @ 2020-03-12 15:04  洪韬  阅读(270)  评论(0编辑  收藏  举报