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
ThunderEX
V2EX  ›  Python

在由字典构成的列表里查找

  •  
  •   ThunderEX · 2012-09-24 15:19:58 +08:00 · 3072 次点击
    这是一个创建于 4239 天前的主题,其中的信息可能已经有所发展或是发生改变。
    listA = [{'ID'=14, ...},
    {'ID'=15, ...},
    ...,
    ]
    写一个简单好看的表达式,如果listA里面有'ID'==14的字典,就返回True?
    10 条回复    1970-01-01 08:00:00 +08:00
    skyleft
        1
    skyleft  
       2012-09-24 15:25:46 +08:00   ❤️ 1
    y=lambda listA:bool([x for x in listA if x['ID']==14])
    reus
        2
    reus  
       2012-09-24 15:26:22 +08:00
    any(map(lambda d: d.get('ID', None) == 14, l))
    013231
        3
    013231  
       2012-09-24 15:27:38 +08:00   ❤️ 2
    any(item['id'] == 14 for item in listA)
    reus
        4
    reus  
       2012-09-24 15:35:48 +08:00   ❤️ 1
    这个比刚才的更快,因为是generator,遇到为True的就直接返回了,不用遍历整个list
    any(d for d in l if d.get('ID', None) == 14)
    比如l = [{'ID': 14}] * 5000000,用这个会秒回,map的话慢很多= =
    ThunderEX
        5
    ThunderEX  
    OP
       2012-09-24 15:37:44 +08:00
    @reus 谢~我们用的是2.4.3没有any()……跪了……
    skyleft
        6
    skyleft  
       2012-09-24 15:47:57 +08:00
    @reus 赞generator
    013231
        7
    013231  
       2012-09-24 15:50:13 +08:00
    @ThunderEX 没有自己寫一個就是了.
    http://gist.github.com/3774827
    ThunderEX
        8
    ThunderEX  
    OP
       2012-09-24 15:53:44 +08:00
    @013231 就是临时用一次,所以问问有没有一个表达式就OK的写得好看,没有的话就老老实实写for好了……
    Veelian
        9
    Veelian  
       2012-09-24 16:28:22 +08:00
    你确定list里是字典?
    ThunderEX
        10
    ThunderEX  
    OP
       2012-09-24 16:32:25 +08:00
    @Veelian 我已经发现自己把冒号写成等号了……
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2151 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 02:28 · PVG 10:28 · LAX 19:28 · JFK 22:28
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.