Python小哥哥

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

2019-03-17  本文已影响0人  我爱学python

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

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

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=['黄莉莉', '袁孝楠']

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

上一篇 下一篇

猜你喜欢

热点阅读