美文网首页
列表插入字典,却总被覆盖问题

列表插入字典,却总被覆盖问题

作者: 小王同学123321 | 来源:发表于2023-04-22 15:03 被阅读0次

    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'}]
    
    

    相关文章

      网友评论

          本文标题:列表插入字典,却总被覆盖问题

          本文链接:https://www.haomeiwen.com/subject/gdgyvrtx.html