Add an item between each item already in the list

2019-02-11 23:40发布

问题:

Possible Duplicate:
python: most elegant way to intersperse a list with an element

Assuming I have the following list:

['a','b','c','d','e']

How can I append a new item (in this case a -) between each item in this list, so that my list will look like the following?

['a','-','b','-','c','-','d','-','e']

Thanks.

回答1:

Here's a solution that I would expect to be very fast -- I believe all these operations will happen at optimized c speed.

def intersperse(lst, item):
    result = [item] * (len(lst) * 2 - 1)
    result[0::2] = lst
    return result

Tested:

>>> l = [1, 2, 3, 4, 5]
>>> intersperse(l, '-')
[1, '-', 2, '-', 3, '-', 4, '-', 5]


回答2:

>>> list('-'.join(ls))
['a', '-', 'b', '-', 'c', '-', 'd', '-', 'e']
>>> 


回答3:

list = ['a', 'b', 'c', 'd', 'e']
result = []
for e in list:
    result.append(e)
    result.append('-')
result.pop()

seems to work



回答4:

This should work with any list elements:

>>> sep = '-'
>>> ls = [1, 2, 13, 14]
>>> sum([[i, '-'] for i in ls], [])[:-1]
[1, '-', 2, '-', 13, '-', 14]


回答5:

The following will add a "separator" element between each of those in a list:

seq = ['a','b','c','d','e']

def tween(seq, sep):
    return reduce(lambda r,v: r+[sep,v], seq[1:], seq[:1])

print tween(seq, '-')

output:

['a', '-', 'b', '-', 'c', '-', 'd', '-', 'e']

FWIW, here's a similar thread titled Custom string joining in the Usenet comp.lang.python group that might interest you.



回答6:

li = ['a','b','c','d','e']
for i in xrange(len(li)-1,0,-1):
    li[i:i] = '-'

or

from operator import concat
seq = ['a','b','c','d','e']
print reduce(concat,[['-',x] for x in seq[1:]],seq[0:1])

or

li = ['a','b','c','d','e']
newli = li[0:1]
[ newli.extend(('-',x)) for x in li[1:]]


回答7:

I think this is a little more elegant/pythonic as well as being general. You may find it less readable if you are not used to a functional style though:

li = ['a','b','c','d','e']

from operator import add
reduce(add, [(elt, "-") for elt in li])[:-1]

If you like, you could use lambda a, b: a+b instead of operator.add.



回答8:

Adapting this answer to a similar question:

>>> input = ['a', 'b', 'c', 'd', 'e']
>>> sep = ['-'] * len(input)
>>> list(sum(zip(input, sep), ())[:-1])
['a', '-', 'b', '-', 'c', '-', 'd', '-', 'e']

Another answer to the same question does this using itertools and a slightly modified separator list:

>>> import itertools
>>> sep = ['-'] * (len(input) - 1)
>>> list(it.next() for it in itertools.cycle((iter(input), iter(sep))))
['a', '-', 'b', '-', 'c', '-', 'd', '-', 'e']