python的代码求助?

2013-05-03 09:24:28 +08:00
 shinerene
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 的应该怎么理解?
3015 次点击
所在节点    Python
6 条回复
liluo
2013-05-03 09:29:22 +08:00
if one:
if rv:
return rv[0]
else:
return None
else:
return rv
liluo
2013-05-03 09:30:55 +08:00
if one:
....if rv:
........return rv[0]
....else:
........return None
else:
....return rv

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

Sqlite API, Django ORM 或者 SQLAlchemy 都支持获取一个的操作,建议使用原生API
e.g. `cur.fetchone()`
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
2013-05-03 16:36:06 +08:00
没有代码缩进好难看啊
不知道v2ex为什么不支持。
shinerene
2013-05-03 23:14:51 +08:00
@liluo
@dreampuf
@xavierskip 嗯嗯 看了中间一行的解释和最后一行的解释 看懂了!
谢谢啦!

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/67560

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX