I have a list like
myl = ['A','B','C','D','E','F'] #length always even
Now my desired output is 'AB','CD','EF'
I tried
>>> myl = ['A','B','C','D','E','F']
>>> even_pos = myl[::2]
>>> odd_pos = myl[::-2]
>>> odd_pos.reverse()
>>> newlist = zip(even_pos,odd_pos)
>>> for x in newlist:
... print "".join(list(x))
...
...
AB
CD
EF
>>>
I don't like this way because I think this is too much.
So, is there any better way to achieve my output.
You can do this concisely using a list comprehension or generator expression:
>>> myl = ['A','B','C','D','E','F']
>>> [''.join(myl[i:i+2]) for i in range(0, len(myl), 2)]
['AB', 'CD', 'EF']
>>> print '\n'.join(''.join(myl[i:i+2]) for i in range(0, len(myl), 2))
AB
CD
EF
You could replace ''.join(myl[i:i+2])
with myl[i] + myl[i+1]
for this particular case, but using the ''.join()
method is easier for when you want to do groups of three or more.
Or an alternative that comes from the documentation for zip()
:
>>> map(''.join, zip(*[iter(myl)]*2))
['AB', 'CD', 'EF']
Why is your method so complicated? You could do basically what you did, but in one line, like so:
[ "".join(t) for t in zip(myl[::2], myl[1::2]) ]
F.J's answer is more efficient though.
list comprehensions
and after seeing then mind = blown
RanRag 2012-04-03 21:08
myl[::-2]
and reversing it in order to get the odd positions. - cha0site 2012-04-03 21:09
How about this?
>>> ["%s%s" % (myl[c], myl[c+1]) for c in range(0, 6, 2)]
['AB', 'CD', 'EF']
I'd probably write:
[myl[i] + myl[i + 1] for i in xrange(len(myl), step=2)]
+
when you're only adding two strings. It's not going to result in quadratic behavior, and might even be a bit faster. And the OP guaranteed that the length is even - Taymon 2012-04-03 21:10