推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
css3
V2EX  ›  Python

两个 list 怎么比较后求出多出来的那值?

  •  
  •   css3 · Nov 6, 2019 · 4456 views
    This topic created in 2555 days ago, the information mentioned may be changed or developed.

    前提是,里边的元素可能是乱序的

    a = [{'key': 1, 'value': 2}, {'key': 3, 'value': 4}]
    
    b = [{'key': 5, 'value': 6}, {'key': 1, 'value': 2}, {'key': 3, 'value': 41} ] # value 不一样的忽略掉
    
    # 想要的结果:
    c = [{'key': 5, 'value': 6}]
    
    11 replies  •  2019-11-07 10:22:36 +08:00
    hehheh
    hehheh
    Nov 6, 2019
    1
    把 key,val 转成 tuple,然后整个 list 打包成 set 然后 intersection
    Cooky
    Cooky
    Nov 6, 2019 via Android
    2
    两边各自合成一个字典做比较
    fdppzrl
    fdppzrl
    Nov 6, 2019 via Android
    3
    c.addAll(a.removeall(b))
    c.addAll(b.removeall(a))
    Java 大概的写法就酱
    ranlan
    ranlan
    Nov 6, 2019
    4
    b = [{'key': 5, 'value': 6}, {'key': 1, 'value': 2}, {'key': 3, 'value': 41} ]中应该是 {'key': 3, 'value': 41} 这个元素应该是 {'key': 3, 'value': 4}吧?
    新手的解法
    c = [i for i in b if i not in a]
    css3
    css3
    OP
    Nov 6, 2019
    5
    @ranlan 不是
    yesterdaysun
    yesterdaysun
    Nov 6, 2019
    6
    ak = set(map(lambda x: x['key'], a))
    bk = set(map(lambda x: x['key'], a))
    c = list(filter(lambda x: x['key'] not in bk, a)) + list(filter(lambda x: x['key'] not in ak, b))
    print(c)
    ranlan
    ranlan
    Nov 6, 2019
    7
    不还意思我理解错了
    应该是这样
    a1 = [x['key'] for x in a]

    c = [i for i in b if i['key'] not in a1]
    css3
    css3
    OP
    Nov 6, 2019
    8
    @yesterdaysun
    @ranlan
    已采纳多谢🤪
    johnnyluck
    johnnyluck
    Nov 6, 2019
    9
    d = set([x['key'] for x in a]) ^ set([y['key'] for y in b])
    c = [x for x in (a+b) if x['key'] in d]
    20015jjw
    20015jjw
    Nov 7, 2019 via Android
    10
    ^ 双关了
    xhxhx
    xhxhx
    Nov 7, 2019
    11
    array_diff
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   5214 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 49ms · UTC 01:27 · PVG 09:27 · LAX 17:27 · JFK 20:27
    ♥ Do have faith in what you're doing.