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

一个 print 的问题

  •  
  •   snoopygao · 2016-05-15 13:07:51 +08:00 · 2927 次点击
    这是一个创建于 2915 天前的主题,其中的信息可能已经有所发展或是发生改变。
    业余学习 python , 只为解决工作生活中的问题
    想打印如下格式,除了这种方法还有其它更 python 的方法吗
    1-2-3-4-5-6

    >>> for i in range(4):
    if i < 3:
    print(i, end='-')
    else:
    print(i)


    0-1-2-3
    10 条回复    2016-05-16 10:42:13 +08:00
    pkuphy
        1
    pkuphy  
       2016-05-15 13:09:51 +08:00
    ```python
    '-'.join([str(i) for i in range(4)])
    ```
    pkuphy
        2
    pkuphy  
       2016-05-15 13:10:36 +08:00   ❤️ 1
    ```
    '-'.join([str(i) for i in range(4)])
    ```
    snoopygao
        3
    snoopygao  
    OP
       2016-05-15 13:17:43 +08:00
    多谢,以前只注意到 split ,没注意到 join
    lunaticus7
        4
    lunaticus7  
       2016-05-15 13:41:55 +08:00
    '-'.join(map(str, range(4)))
    不过按照现在的趋势, map 不太推荐使用了
    SakuraSa
        5
    SakuraSa  
       2016-05-15 13:54:27 +08:00   ❤️ 1
    既然是 py3 的话,是不是可以这样:

    print(*range(4),sep='-')
    junnplus
        6
    junnplus  
       2016-05-15 14:02:02 +08:00
    发现 ruby 写起来好优雅
    (1..4).to_a.join('-')
    billlee
        7
    billlee  
       2016-05-15 14:15:31 +08:00
    '-'.join((str(i) for i in range(4)))
    yhylord
        8
    yhylord  
       2016-05-15 20:06:49 +08:00
    @lunaticus7 为什么不推荐用 map 呢?
    lunaticus7
        9
    lunaticus7  
       2016-05-16 09:46:39 +08:00
    @yhylord 推荐使用 list comprehension 取代 map 、 filter 等函数,更自由,并且表现力更高。
    成文的规定可以参考:
    https://google.github.io/styleguide/pyguide.html#Deprecated_Language_Features

    # map and filter
    map(lambda x:x+1, filter(lambda x:x%3, range(10)))
    # same as LC
    [x+1 for x in range(10) if x%3]
    mornlight
        10
    mornlight  
       2016-05-16 10:42:13 +08:00
    @lunaticus7 map,reduce,filter 是函数式编程的思维,直接建议用其他方式替代是不是太粗暴了,那个 guide 原文里的意思是这些函数的参数里有 lambda 表达式时考虑替代。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3461 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 11:41 · PVG 19:41 · LAX 04:41 · JFK 07:41
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.