将list/dict作为参数传递给函数,与直接在函数中修改它相比,有什么优点/缺点吗?

2024-05-05 05:42:00 发布

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

这样做有什么好处或坏处吗

listtt =[1]
dicto = {'a':2}

def ffun():
    listtt.append(2)
    dicto['b'] = 3

ffun()
print(listtt)
print(dicto)

[1, 2] {'a': 2, 'b': 3}

与此对比

listtt =[1]
dicto = {'a':2}

def ffun(hh, hh2):
    hh.append(2)
    hh2['b'] = 3

ffun(listtt, dicto)
print(listtt)
print(dicto)

[1, 2] {'a': 2, 'b': 3}


Tags: defhhprintappend坏处listtthh2dicto
1条回答
网友
1楼 · 发布于 2024-05-05 05:42:00

*嗨

我可能过于简单化了这一点,但通过dict和清单,即使是一个非常高的量,那么你有什么不会引起任何问题。Python通过对象引用传递参数,所以没有内存操作,在这两种情况下性能应该相同。 尽管如此,您仍然需要重新考虑为什么首先要使用全局变量。卡娅已经在评论中链接了一个关于全局变量的讨论。值得一读*

相关问题 更多 >