Python3向函数传递列表

2024-06-01 02:48:54 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python3中,我目前正在尝试使用函数修改列表。(顺便说一下,对Python非常陌生:)

我会给你指出问题的方向,作为参考。在

“编写一个名为make_great()的函数,通过在每个魔术师的名字中添加短语'the great'来修改魔术师列表。调用show_魔术师()查看列表是否已实际修改。“

magicians = ['larry', 'mo', 'curly', 'nate']

def printing_magicians(names):
    """Printing the magicians names"""
    for name in names:
        print(name.title())

printing_magicians(magicians)

def make_great(names):
    """Adding 'the Great' to each magician"""
    for name in names:
        print(names + " the Great")

我不知道从这里到哪里去。我不知道为make_great()函数调用什么参数,然后我不知道如何应用show_魔术师()函数来查看已修改的列表。任何帮助都会很棒!提前谢谢。在


Tags: the函数namein列表formakenames
3条回答

这是一行中的方法。基本思想是使用列表理解并通过切片[:]修改列表的所有元素。在

def make_great(names):
    """Adding 'the Great' to each magician"""
    names[:] = [name + ' the Great' for name in names]

show_magicians函数只打印magicians,因为magicians变量在全局范围内。在

^{pr2}$

示例:

>>> make_great(magicians)
>>> show_magicians()
['larry the Great', 'mo the Great', 'curly the Great', 'nate the Great']

要就地修改列表,应按其索引引用列表中的每个项:

def make_great(names):
    for i in range(len(names)):
        names[i] += " the Great"

Python中的惯用用法是在需要索引时用enumerate()遍历列表。它将为您提供列表索引中的值和,以便您可以:

def make_great(names):
    for i, name in enumerate(names):
        names[i] = f'{name} the Great'

相关问题 更多 >