美文网首页Python小哥哥
在 Python 中如何向函数传递列表

在 Python 中如何向函数传递列表

作者: 我爱学python | 来源:发表于2019-03-17 14:06 被阅读0次

    把列表传递给函数后, 函数就能直接访问列表中的内容咯。

    假设有一组专家,我们想邀请他们参加研讨会。

    def send_invitation(experts):
        '''发送邀请函'''
        for expert in experts:
            print(expert + ',您好,现邀请您参加 XX 研讨会...')
    
    
    experts = ['袁孝楠', '黄莉莉']
    send_invitation(experts)
    

    运行结果:

    袁孝楠,您好,现邀请您参加 XX 研讨会...

    黄莉莉,您好,现邀请您参加 XX 研讨会...

    1 修改列表

    列表参数传递给函数后, 函数就可以对其进行修改。注意:在函数中对列表所进行的任何修改都是永久性的。

    def send_invitation(experts, informed):
        '''发送邀请函,并移动列表数据到【已通知】列表'''
        while experts:
            expert = experts.pop()
            print(expert + ',您好,现邀请您参加 XX 研讨会...')
            informed.append(expert)
    
    
    experts = ['袁孝楠', '黄莉莉']  # 专家列表
    informed = []  # 已通知人员列表
    print('执行前:experts=' + str(experts) + ',informed=' + str(informed))
    send_invitation(experts, informed)
    print('执行后:experts=' + str(experts) + ',informed=' + str(informed))
    

    运行结果:

    执行前:experts=['袁孝楠', '黄莉莉'],informed=[]

    黄莉莉,您好,现邀请您参加 XX 研讨会...

    袁孝楠,您好,现邀请您参加 XX 研讨会...

    执行后:experts=[],informed=['黄莉莉', '袁孝楠']

    • 即使没有注释,那些具有描述性的函数名也能清晰地表达出函数所做的工作。
    • 我们也可以在一个函数中调用另一个函数, 这样有助于将复杂的任务分解为一系列的步骤,让程序变得更具可读性。

    2 只读列表

    有时候,我们并不想让函数修改传递进去的列表,这时我们可以向函数传递列表的副本:

    experts = ['袁孝楠', '黄莉莉']  # 专家列表
    informed = []  # 已通知人员列表
    print('执行前:experts=' + str(experts) + ',informed=' + str(informed))
    send_invitation(experts[:], informed)
    print('执行后:experts=' + str(experts) + ',informed=' + str(informed))
    

    运行结果:

    执行前:experts=['袁孝楠', '黄莉莉'],informed=[]

    黄莉莉,您好,现邀请您参加 XX 研讨会...

    袁孝楠,您好,现邀请您参加 XX 研讨会...

    执行后:experts=['袁孝楠', '黄莉莉'],informed=['黄莉莉', '袁孝楠']

    虽然向函数传递列表的副本可以保留原始列表的内容, 但除非有充分的理由需要这样做。因为让函数使用传递进行的列表可以避免花时间在内存中创建副本, 从而提高性能, 这在处理大数据列表时尤其需要注意。

    相关文章

      网友评论

        本文标题:在 Python 中如何向函数传递列表

        本文链接:https://www.haomeiwen.com/subject/dxkumqtx.html