更新插入可变类型的嵌套数据类型要注意 & 不要用列表,字典等可变类型作为函数的默认参数

问题1:更新插入可变类型的嵌套数据类型要注意

先看一段代码

if __name__ == '__main__':
    tx1 = {'from': 'Jason', 'to': 'Karmen'}
    tx2 = {'from': 'Jason', 'to': 'Karmen'}
    # id(txs[0]) = id(tx1) & id(txs[1]) = id(tx2)
    txs = [tx1, tx2]
    # [{'to': 'Karmen', 'from': 'Jason'}, {'to': 'Karmen', 'from': 'Jason'}]
    print txs

    # 往tx1新增一个键,txs也会更新
    tx1['?'] = '?'
    tx1['from'] = 'God'
    # [{'to': 'Karmen', 'from': 'God', '?': '?'}, {'to': 'Karmen', 'from': 'Jason'}]
    print txs

    mylist = []
    # id(mylist[0]) = id(tx1)
    mylist.append(tx1)
    mylist[0]['from'] = 'SKY'
    # [{'to': 'Karmen', 'from': 'SKY', '?': '?'}, {'to': 'Karmen', 'from': 'Jason'}]
    print txs
    # [{'to': 'Karmen', 'from': 'SKY', '?': '?'}]
    print mylist

    # id(mylist[0]) = id(mylist[1]) = id(tx1)
    mylist.append(tx1)
    mylist[1]['to'] = 'RAINBOW'
    # [{'to': 'RAINBOW', 'from': 'SKY', '?': '?'}, {'to': 'Karmen', 'from': 'Jason'}]
    print txs
    # [{'to': 'RAINBOW', 'from': 'SKY', '?': '?'}, {'to': 'RAINBOW', 'from': 'SKY', '?': '?'}]
    print mylist

结果为:

[{'to': 'Karmen', 'from': 'Jason'}, {'to': 'Karmen', 'from': 'Jason'}]
[{'to': 'Karmen', 'from': 'God', '?': '?'}, {'to': 'Karmen', 'from': 'Jason'}]
[{'to': 'Karmen', 'from': 'SKY', '?': '?'}, {'to': 'Karmen', 'from': 'Jason'}]
[{'to': 'Karmen', 'from': 'SKY', '?': '?'}]
[{'to': 'RAINBOW', 'from': 'SKY', '?': '?'}, {'to': 'Karmen', 'from': 'Jason'}]
[{'to': 'RAINBOW', 'from': 'SKY', '?': '?'}, {'to': 'RAINBOW', 'from': 'SKY', '?': '?'}]

问题2: 不要用列表,字典等可变类型作为函数的默认参数

先看一段代码

def f(x,l=[]):
    for i in range(x):
        l.append(i*i)
    print(l)

print('---1---')
f(4)
print('---2---')
f(5)

执行结果:

---1---
[0, 1, 4, 9]
---2---
[0, 1, 4, 9, 0, 1, 4, 9, 16]

预期的结果为:

---1---
[0, 1, 4, 9]
---2---
[0, 1, 4, 9, 16]

问题解释

当定义函数时,会保存函数中默认参数list的值,即保存list的id。

  1. 在第一次调用的时候往该list进行了插入,那么list的id不变内容变了。
  2. 在第二次调用的时候仍取同一个id,所以又往同一个list插入,则在第一次调用的基础上继续插入。

问题解决

def f(x,l=None):
    if l is None:
        l = []
    for i in range(x):
        l.append(i*i)
    print(l)


print('---1---')
f(4)
print('---2---')
f(5)
print('---3---')
f(6)

结果:

---1---
[0, 1, 4, 9]
---2---
[0, 1, 4, 9, 16]
---3---
[0, 1, 4, 9, 16, 25]

猜你喜欢

转载自blog.csdn.net/jason_cuijiahui/article/details/80066446