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

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

  •  
  •   napoleonu · 2014-05-30 22:30:45 +08:00 · 8307 次点击
    这是一个创建于 3612 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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' 有时候要引号,有时候不需要。
    5 条回复    2014-05-31 10:29:30 +08:00
    dbow
        1
    dbow  
       2014-05-30 23:34:47 +08:00   ❤️ 3
    s = (('a',), ('b',), ('c',), ('d',), ('e',), ('f',))

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


    这样: ",".join(["'%s'" % x[0] for x in s])
    manfay
        2
    manfay  
       2014-05-31 00:00:27 +08:00   ❤️ 1
    (item[0] for item in Tuple)
    napoleonu
        3
    napoleonu  
    OP
       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
        4
    skydiver  
       2014-05-31 02:23:58 +08:00
    直接一条SQL语句查出来算了。。多优雅
    mckelvin
        5
    mckelvin  
       2014-05-31 10:29:30 +08:00 via Android
    拼接字符串是一件危险的事情,应当谨慎使用。

    http://blog.xupeng.me/2013/09/25/mysqldb-args-processing/ 这篇博文可能有参考意义
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2910 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 03:51 · PVG 11:51 · LAX 20:51 · JFK 23:51
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.