V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
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 · Sep 24, 2012 · 3764 views
    This topic created in 4967 days ago, the information mentioned may be changed or developed.
    listA = [{'ID'=14, ...},
    {'ID'=15, ...},
    ...,
    ]
    写一个简单好看的表达式,如果listA里面有'ID'==14的字典,就返回True?
    10 replies    1970-01-01 08:00:00 +08:00
    skyleft
        1
    skyleft  
       Sep 24, 2012   ❤️ 1
    y=lambda listA:bool([x for x in listA if x['ID']==14])
    reus
        2
    reus  
       Sep 24, 2012
    any(map(lambda d: d.get('ID', None) == 14, l))
    013231
        3
    013231  
       Sep 24, 2012   ❤️ 2
    any(item['id'] == 14 for item in listA)
    reus
        4
    reus  
       Sep 24, 2012   ❤️ 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
       Sep 24, 2012
    @reus 谢~我们用的是2.4.3没有any()……跪了……
    skyleft
        6
    skyleft  
       Sep 24, 2012
    @reus 赞generator
    013231
        7
    013231  
       Sep 24, 2012
    @ThunderEX 没有自己寫一個就是了.
    http://gist.github.com/3774827
    ThunderEX
        8
    ThunderEX  
    OP
       Sep 24, 2012
    @013231 就是临时用一次,所以问问有没有一个表达式就OK的写得好看,没有的话就老老实实写for好了……
    Veelian
        9
    Veelian  
       Sep 24, 2012
    你确定list里是字典?
    ThunderEX
        10
    ThunderEX  
    OP
       Sep 24, 2012
    @Veelian 我已经发现自己把冒号写成等号了……
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2140 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 00:47 · PVG 08:47 · LAX 17:47 · JFK 20:47
    ♥ Do have faith in what you're doing.