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

关于tuple([1])的疑问?

  •  
  •   brikhoff · 2013-10-08 22:54:15 +08:00 · 3213 次点击
    这是一个创建于 3851 天前的主题,其中的信息可能已经有所发展或是发生改变。
    tuple([1]) = (1,)
    这个深入python里面也解释过:为创建单元素元组,需要在值之后加上一个逗号。没有逗号,Python 会假定这只是一对额外的圆括号,虽然没有害处,但并不创建元组。
    其实我想问的是,如果在进行SQL IN 查询的时候,我最开始出来的时候会str(tuple([1, 2, 5, 9]))来生成'(1, 2 , 5, 9)'的字符串来连接查询,但是这样在1 == len(pid_list)的时候就会出现上面的问题,最后str([1, 2, 5, 9]).replace('[', '(').replace(']', ')')这样来实现。
    虽然说有时候写代码,只要能实现这个功能就可以了,但是我想想也知道这个方法很笨,我想问问有没有其他更好的方法。写python不多,感觉肯定有我不知道的方法。
    6 条回复    1970-01-01 08:00:00 +08:00
    ericls
        1
    ericls  
       2013-10-08 23:21:41 +08:00 via Android
    1 == len(pid_list)
    是什么问题?
    vmebeh
        2
    vmebeh  
       2013-10-08 23:23:37 +08:00
    最好不要直接拼接,文档有例子

    http://docs.python.org/2/library/sqlite3.html#cursor-objects
    farseerfc
        3
    farseerfc  
       2013-10-08 23:26:14 +08:00
    沒理解清楚你的問題。你是說,你有一個list是pid_list,然後想最快得到它的'(1,2,3,4)'這樣的形式所以這麼寫str(tuple(pid_list)),並且不想要len(pid_list)==1時最後的那個逗號是麼?
    你的方法不笨。Python裏面做事情一般只有一種做法,越清晰可讀越好,你的方法就很可讀。
    如果是我的話,會這麼寫: '(%s)'%str(pid_list)[1:-1]
    est
        4
    est  
       2013-10-09 00:58:05 +08:00
    ','.join()
    likexian
        5
    likexian  
       2013-10-09 09:33:23 +08:00
    有join不用,用什么str,str是这样用的吗
    brikhoff
        6
    brikhoff  
    OP
       2013-10-09 10:10:15 +08:00
    @likexian join + map?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3274 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 13:08 · PVG 21:08 · LAX 06:08 · JFK 09:08
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.