开发者

Add an item between each item already in the list [duplicate]

This question already has answers h开发者_运维知识库ere: Closed 10 years ago.

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.


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]

The line that does all the work, result[0::2] = lst, uses extended slicing and slice assignment. The third step parameter tells python to assign values from lst to every second position in l.


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


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

seems to work


This should work with any list elements:

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


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.


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:]]


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.


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']
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜