List comprehension without [ ] in Python

后端 未结 7 2274
悲&欢浪女
悲&欢浪女 2020-11-21 05:28

Joining a list:

>>> \'\'.join([ str(_) for _ in xrange(10) ])
\'0123456789\'

join must take an iterable.

Appa

7条回答
  •  再見小時候
    2020-11-21 05:44

    >>>''.join( str(_) for _ in xrange(10) )
    

    This is called a generator expression, and is explained in PEP 289.

    The main difference between generator expressions and list comprehensions is that the former don't create the list in memory.

    Note that there's a third way to write the expression:

    ''.join(map(str, xrange(10)))
    

提交回复
热议问题