python tuple 到 mysql in (list)怎么转换?

2014-05-30 22:30:45 +08:00
 napoleonu
mysql的返回值可以是tuple也可以是dict,常用的时tuple。

有时候想要根据前一个SQL的结果去生成另一个SQL,比如:

sql1 = select id,name from article limit 10;

sql2 = select * from reply where article_id in (sql1.id);

如是就有了下面的问题:

(('a',), ('b',), ('c',), ('d',), ('e',), ('f',))

'a','b','c','d','e','f'
怎么做到呢?


(('a',1), ('b',2), ('c',3), ('d',4), ('e',5), ('f',6))

'a','b','c','d','e','f'
还有这种。

我现在的做法是 拼接字符串。觉得好傻。

或者你的拼接字符串很高效也希望可以学习下,注:'a','b' 有时候要引号,有时候不需要。
8331 次点击
所在节点    Python
5 条回复
dbow
2014-05-30 23:34:47 +08:00
s = (('a',), ('b',), ('c',), ('d',), ('e',), ('f',))

'a','b','c','d','e','f'


这样: ",".join(["'%s'" % x[0] for x in s])
manfay
2014-05-31 00:00:27 +08:00
(item[0] for item in Tuple)
napoleonu
2014-05-31 00:44:47 +08:00
@dbow 非常感谢。(('a',1), ('b',2), ('c',3), ('d',4), ('e',5), ('f',6))是一样的,比我优雅的多的拼接字符串,哈。

我这到了这个,不再拼接字符串:
>>> a=(('a',1), ('b',2), ('c',3), ('d',4), ('e',5), ('f',6))
>>> id,name = zip(*a)
>>> print str(id);
('a', 'b', 'c', 'd', 'e', 'f')
>>> print str(name);
(1, 2, 3, 4, 5, 6)
skydiver
2014-05-31 02:23:58 +08:00
直接一条SQL语句查出来算了。。多优雅
mckelvin
2014-05-31 10:29:30 +08:00
拼接字符串是一件危险的事情,应当谨慎使用。

http://blog.xupeng.me/2013/09/25/mysqldb-args-processing/ 这篇博文可能有参考意义

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

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

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

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

© 2021 V2EX