问题描述
使用 list 的append() 方法,前边的数据总是被后边的数据覆盖
有问题代码
def process():
proxies = {'180.97.104.97:80': '{"proxy": "180.97.104.97:80"}', \
'123.125.114.18:80': '{"proxy": "123.125.114.18:80"}', \
'123.125.115.242:80': '{"proxy": "123.125.115.242:80"}'}
proxy_dict = {} # 在循环外部定义字典
cnt = 0
proxy_list = []
for proxy in proxies:
print(proxy)
ip, port = proxy.split(":")
proxy_dict['ip'] = ip
proxy_dict['port'] = port
proxy_list.append(proxy_dict)
cnt += 1
print('total ip: ', cnt)
return proxy_list
good_proxy = process()
print(good_proxy)
执行结果
发现list 中的数据全都是字典的最后一个数据。
[root@2c9a57af434c test]# python test.py
total ip: 3
[{'ip': '123.125.115.242', 'port': '80'}, {'ip': '123.125.115.242', 'port': '80'}, {'ip': '123.125.115.242', 'port': '80'}]
解决方法
代码
```python
def process():
proxies = {'180.97.104.97:80': '{"proxy": "180.97.104.97:80"}', \
'123.125.114.18:80': '{"proxy": "123.125.114.18:80"}', \
'123.125.115.242:80': '{"proxy": "123.125.115.242:80"}'}
cnt = 0
proxy_list = []
for proxy in proxies:
proxy_dict = {} # 字典定义在循环内部
ip, port = proxy.split(":")
proxy_dict['ip'] = ip
proxy_dict['port'] = port
proxy_list.append(proxy_dict)
cnt += 1
print('total ip: ', cnt)
return proxy_list
good_proxy = process()
print(good_proxy)
执行结果
字典中的每一个元素,被放在list 中。
[root@2c9a57af434c test]# python test.py
total ip: 3
[{'ip': '180.97.104.97', 'port': '80'}, {'ip': '123.125.114.18', 'port': '80'}, {'ip': '123.125.115.242', 'port': '80'}]
解释
dict 定义在循环外,只有一个地址,每次循环,地址不变,所以覆盖了前边的数据。可以从浅拷贝和深拷贝的方面来理解。
Python中的对象之间赋值时是按引用传递的,如果需要拷贝对象,需要使用标准库中的copy模块。
- copy.copy 浅拷贝 只拷贝父对象,不会拷贝对象的内部的子对象。
- copy.deepcopy 深拷贝 拷贝对象及其子对象