推荐学习书目
› 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
panda0
V2EX  ›  Python

这段代码如何 pythonic?

  •  
  •   panda0 · Aug 24, 2016 · 1664 views
    This topic created in 3688 days ago, the information mentioned may be changed or developed.

    查询数据库所有id在list里的文章,加入article_list.

    article_list = []
    for i in range(0, len(list)):
        cur.execute('select * from articles where id = {}'.format(list[i]))
        article_list.append(cur.fetchone())
    

    怎么把上面的一句话写成一句 python 语句呢?

    article_list.append(
        cur.execute('select * from articles where id = {}'.format(list[i]))
           for i in range(0, len(list))
                        )
    

    这么写,返回article_list是[<generator object <genexpr> at 0x10e112960>].似乎并没有拿到具体的值append.

    panda0
        1
    panda0  
    OP
       Aug 24, 2016
    ```python
    article_list = [cur.fetchone() for i in list if cur.execute('select * from articles where id = {}'.format(i[2])) or 1]
    ```
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   5189 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 02:18 · PVG 10:18 · LAX 19:18 · JFK 22:18
    ♥ Do have faith in what you're doing.