i'm lost in list manipulation
Paul Watson
pwatson at redlinec.com
Wed Mar 3 16:53:18 EST 2004
"GrelEns" <grelens at NOSPAMyahoo.NOTNEEDEDfr> wrote in message
news:40460bb3$0$28116$636a15ce at news.free.fr...
> hello,
>
> having a list like ['a', 'b', 'c', 'd'] i would like to get
>
> [['a', '-', 'b', 'c', 'd'],
> ['a', 'b', '-', 'c', 'd'],
> ['a', 'b', 'c', '-', 'd'],
> ['a', '-', 'b', '-', 'c', 'd'],
> ['a', 'b', '-', 'c', '-', 'd'],
> ['a', '-', 'b', '-', 'c','-', 'd']]
>
> that is adding successively an item between at all the available place,
and
> i just can't get my brain doing that :(
>
> thank a lot if you could help...
Does this look like it would work?
alist = ['a', 'b', 'c', 'd']
nlist = range(len(alist) - 1)
finallist = []
for x in range(2 ** (len(alist) - 1)):
if x == 0: continue #remove this if you want one with no dashes
rlist = [alist[0]]
for y in nlist:
if x & (1 << y): rlist.append('-')
rlist.append(alist[y + 1])
finallist.append(rlist)
del rlist
print finallist
$ ./listins.py
[['a', '-', 'b', 'c', 'd'], ['a', 'b', '-', 'c', 'd'], ['a', '-', 'b', '-',
'c', 'd'], ['a', 'b', 'c', '-', 'd'], ['a',
'-', 'b', 'c', '-', 'd'], ['a', 'b', '-', 'c', '-', 'd'], ['a', '-', 'b',
'-', 'c', '-', 'd']]
More information about the Python-list
mailing list