简体   繁体   中英

Is there a str.join() for lists?

I understand str.join() :

>>> '|'.join(['1','2','3'])
'1|2|3'

Is there something which outputs a list? Is there a function that will output:

['1', '|', '2','|', '3']

That is, a str.join() for lists? (or any other iterable?)

list('|'.join(['1','2','3']))

should do the trick where you are working with a list of chars.

A more generic solution, that works for all objects is:

from itertools import izip_longest, chain

def intersperse(myiter, value):
    return list(
        chain.from_iterable(izip_longest(myiter, [], fillvalue=value))
    )[:-1]

I'm not aware of a built-in/std-library version of this function.

In action:

print intersperse([1,2,3], '|')

outputs:

[1, '|', 2, '|', 3]

How about this?

>>> list('|'.join(['1','2','3']))
['1', '|', '2', '|', '3']
a = [1, 2, 'str', 'foo']
print [x for y in a for x in y, '|'][:-1]
# [1, '|', 2, '|', 'str', '|', 'foo']

For the general case, consider the roundrobin itertools recipe

This simple generator avoids building a list (faster, saves memory):

def intersperse(iterable, element):
    iterable = iter(iterable)
    yield next(iterable)
    while True:
        next_from_iterable = next(iterable)
        yield element
        yield next_from_iterable

Example:

>>> list(intersperse(['1', '2', '3'], '|'))
['1', '|', '2', '|', '3']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM