Add an item between each item already in the list

2019-02-11 23:34发布

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.

8条回答
来,给爷笑一个
2楼-- · 2019-02-12 00:06
>>> list('-'.join(ls))
['a', '-', 'b', '-', 'c', '-', 'd', '-', 'e']
>>> 
查看更多
女痞
3楼-- · 2019-02-12 00:07

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.

查看更多
别忘想泡老子
4楼-- · 2019-02-12 00:08
list = ['a', 'b', 'c', 'd', 'e']
result = []
for e in list:
    result.append(e)
    result.append('-')
result.pop()

seems to work

查看更多
The star\"
5楼-- · 2019-02-12 00:10

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]
查看更多
Ridiculous、
6楼-- · 2019-02-12 00:12
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楼-- · 2019-02-12 00:17

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']
查看更多
登录 后发表回答