推荐学习书目
› 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 · May 15, 2016 · 3812 views
    This topic created in 3841 days ago, the information mentioned may be changed or developed.
    业余学习 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 replies  •  2016-05-16 10:42:13 +08:00
    pkuphy
    pkuphy
    May 15, 2016
    1
    ```python
    '-'.join([str(i) for i in range(4)])
    ```
    pkuphy
    pkuphy
    May 15, 2016❤️1
    2
    ```
    '-'.join([str(i) for i in range(4)])
    ```
    snoopygao
    snoopygao
    OP
    May 15, 2016
    3
    多谢,以前只注意到 split ,没注意到 join
    lunaticus7
    lunaticus7
    May 15, 2016
    4
    '-'.join(map(str, range(4)))
    不过按照现在的趋势, map 不太推荐使用了
    SakuraSa
    SakuraSa
    May 15, 2016❤️1
    5
    既然是 py3 的话,是不是可以这样:

    print(*range(4),sep='-')
    junnplus
    junnplus
    May 15, 2016
    6
    发现 ruby 写起来好优雅
    (1..4).to_a.join('-')
    billlee
    billlee
    May 15, 2016
    7
    '-'.join((str(i) for i in range(4)))
    yhylord
    yhylord
    May 15, 2016
    8
    @lunaticus7 为什么不推荐用 map 呢?
    lunaticus7
    lunaticus7
    May 16, 2016
    9
    @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
    mornlight
    May 16, 2016
    10
    @lunaticus7 map,reduce,filter 是函数式编程的思维,直接建议用其他方式替代是不是太粗暴了,那个 guide 原文里的意思是这些函数的参数里有 lambda 表达式时考虑替代。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   927 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 21:09 · PVG 05:09 · LAX 13:09 · JFK 16:09
    ♥ Do have faith in what you're doing.