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

这是什么用法?

  •  
  •   haython · 2014-09-17 23:45:31 +08:00 · 3037 次点击
    这是一个创建于 3509 天前的主题,其中的信息可能已经有所发展或是发生改变。
    a = [1, 2, 3, 4]
    print(','.join('%s' % id for id in a))

    join里边的这段是什么意思?
    4 条回复    2014-09-18 22:06:51 +08:00
    kzing
        1
    kzing  
       2014-09-18 00:25:30 +08:00   ❤️ 1
    join里面是一个生成器表达式, '%s'用来转字符串. 相当于以下用法.

    ','.join(str(id) for id in a)

    # or

    ','.join(map(str, a))
    hiddenman
        2
    hiddenman  
       2014-09-18 16:05:16 +08:00
    多看看Python基础书籍。
    Melodic
        3
    Melodic  
       2014-09-18 19:20:52 +08:00   ❤️ 1
    人家问join里面的 是什么意思 - -就是表推导嘛
    billlee
        4
    billlee  
       2014-09-18 22:06:51 +08:00   ❤️ 1
    '%s' % id 是把变量 id format 成字符串
    ('%s' % id for id in a) 是一个 generator, 就是字面的意义,迭代 a 中的每个元素 id, 返回 '%s' % id
    如果把圆括号改成放括号,即 ['%s' % id for id in a], 就是返回一个列表 ['1', '2', '3', '4']
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1267 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 18:05 · PVG 02:05 · LAX 11:05 · JFK 14:05
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.