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

python的代码求助?

  •  
  •   shinerene ·
    Xiechen · 2013-05-03 09:24:28 +08:00 · 3010 次点击
    这是一个创建于 4012 天前的主题,其中的信息可能已经有所发展或是发生改变。
    def query_db(query,args = (),one=False):
    """QUeries the database and returns a list of dictionaries."""
    cur = get_db().execute(query,args)
    rv = cur.fetchall()
    return (rv[0] if rv else None) if one else rv


    最后一句return 的应该怎么理解?
    6 条回复    1970-01-01 08:00:00 +08:00
    liluo
        1
    liluo  
       2013-05-03 09:29:22 +08:00
    if one:
    if rv:
    return rv[0]
    else:
    return None
    else:
    return rv
    liluo
        2
    liluo  
       2013-05-03 09:30:55 +08:00
    if one:
    ....if rv:
    ........return rv[0]
    ....else:
    ........return None
    else:
    ....return rv

    代码缩进不能,请将 . 脑补成空格.
    dreampuf
        3
    dreampuf  
       2013-05-03 13:03:59 +08:00
    三元操作符的组合判断。

    Sqlite API, Django ORM 或者 SQLAlchemy 都支持获取一个的操作,建议使用原生API
    e.g. `cur.fetchone()`
    xavierskip
        4
    xavierskip  
       2013-05-03 13:23:51 +08:00
    中间的那一行是这个吧:
    rv = [dict((cur.description[idx][0].lower(), value) for idx, value in enumerate(row)) for row in cur.fetchall()]

    lz看明白这一行没?!


    (True: do...) if xxx else (False: do...)
    hhrmatata
        5
    hhrmatata  
       2013-05-03 16:36:06 +08:00
    没有代码缩进好难看啊
    不知道v2ex为什么不支持。
    shinerene
        6
    shinerene  
    OP
       2013-05-03 23:14:51 +08:00
    @liluo
    @dreampuf
    @xavierskip 嗯嗯 看了中间一行的解释和最后一行的解释 看懂了!
    谢谢啦!
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2785 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 05:35 · PVG 13:35 · LAX 22:35 · JFK 01:35
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.