V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2019-11-06 17:58:42 +08:00 · 3064 次点击
    这是一个创建于 1605 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    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 条回复    2019-11-07 10:22:36 +08:00
    hehheh
        1
    hehheh  
       2019-11-06 18:02:33 +08:00
    把 key,val 转成 tuple,然后整个 list 打包成 set 然后 intersection
    Cooky
        2
    Cooky  
       2019-11-06 18:05:10 +08:00 via Android
    两边各自合成一个字典做比较
    fdppzrl
        3
    fdppzrl  
       2019-11-06 18:11:30 +08:00 via Android
    c.addAll(a.removeall(b))
    c.addAll(b.removeall(a))
    Java 大概的写法就酱
    ranlan
        4
    ranlan  
       2019-11-06 18:14:17 +08:00
    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
        5
    css3  
    OP
       2019-11-06 18:21:59 +08:00
    @ranlan 不是
    yesterdaysun
        6
    yesterdaysun  
       2019-11-06 18:32:06 +08:00
    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
        7
    ranlan  
       2019-11-06 18:35:19 +08:00
    不还意思我理解错了
    应该是这样
    a1 = [x['key'] for x in a]

    c = [i for i in b if i['key'] not in a1]
    css3
        8
    css3  
    OP
       2019-11-06 18:59:47 +08:00
    @yesterdaysun
    @ranlan
    已采纳多谢🤪
    johnnyluck
        9
    johnnyluck  
       2019-11-06 21:46:53 +08:00
    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
        10
    20015jjw  
       2019-11-07 08:11:59 +08:00 via Android
    ^ 双关了
    xhxhx
        11
    xhxhx  
       2019-11-07 10:22:36 +08:00
    array_diff
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2815 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 13:30 · PVG 21:30 · LAX 06:30 · JFK 09:30
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.