django项目中遇到bug,总是遇到同一域名出现多个同一ip(域名和ip之间是多对多映射),后面检索到的域名覆盖前面域名,举例如下:
>>> listcontaindict=[{1:"a",2:"b"},{2:"b",3:"c"},{1:"a",3:"c"},{4:"d"}]
>>> tarlist=list()
>>> for line in listcontaindict:
... if line.get(4) == "d":
... line[5]="e"
... tarlist.append(line)
...
>>> tarlist
[{4: 'd', 5: 'e'}]
>>> for line in listcontaindict:
... if line.get(4) == "d":
... line[5]="f"
... tarlist.append(line)
...
>>> tarlist
[{4: 'd', 5: 'f'}, {4: 'd', 5: 'f'}]
问题原因:引用列表中字典的同一块内存地址引起
解决方案:
>>> tarlist=list()
>>> listcontaindict=[{1:"a",2:"b"},{2:"b",3:"c"},{1:"a",3:"c"},{4:"d"}]
>>> for line in listcontaindict:
... if line.get(4) == "d":
... lined=line.copy()
... lined[5]="e"
... tarlist.append(lined)
...
>>> for line in listcontaindict:
... if line.get(4) == "d":
... lined=line.copy()
... lined[5]="f"
... tarlist.append(lined)
...
>>> tarlist
[{4: 'd', 5: 'e'}, {4: 'd', 5: 'f'}]
网友评论