这段代码如何 pythonic?

2016-08-24 15:54:48 +08:00
 panda0

查询数据库所有idlist里的文章,加入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.

1101 次点击
所在节点    Python
1 条回复
panda0
2016-08-24 16:16:49 +08:00
```python
article_list = [cur.fetchone() for i in list if cur.execute('select * from articles where id = {}'.format(i[2])) or 1]
```

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

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

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

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

© 2021 V2EX