i had a list:
list = ['a', 'b', 'c', 'd', 'e', 'f']
how would I go about converting this list to:
list = ['ab', 'cd', 'ef']
Thanks in advance!
i had a list:
list = ['a', 'b', 'c', 'd', 'e', 'f']
how would I go about converting this list to:
list = ['ab', 'cd', 'ef']
Thanks in advance!
Given:
>>> li=['a', 'b', 'c', 'd', 'e', 'f']
You can use zip:
>>> ['{}{}'.format(a,b) for a,b in zip(li, li[1:])]
['ab', 'bc', 'cd', 'de', 'ef']
Or:
>>> [a+b for a,b in zip(li, li[1:])]
['ab', 'bc', 'cd', 'de', 'ef']
Or, if you want ['ab', 'cd', 'ef']
you can do:
>>> [a+b for a,b in zip(*[iter(li)]*2)]
['ab', 'cd', 'ef']
Or,
>>> [a+b for a,b in zip(li[::2],li[1::2])]
['ab', 'cd', 'ef']
For a different group length:
>>> [''.join(l) for l in zip(*[iter(li)]*3)]
['abc', 'def']
(And please don't use list
as a name for a list. You clobber the function by the same name)
def pairs(sequence):
sequence = iter(sequence)
while True:
yield next(sequence) + next(sequence)
>>> list(pairs(['a', 'b', 'c', 'd']))
['ab', 'cd']
>>> list(pairs(['a', 'b', 'c']))
['ab']
Note that it would ignore elements when the total number is not even.
You have many ways, here is one:
[n for n in map(lambda x: x[0]+x[1], zip(list[::2], list[1::2]))]
Reason I don't use list()
to force output is because you are occupying it, which is not recommended. If you rename your list
to ls
, here is a shorter version:
list(map(lambda x: x[0]+x[1], zip(ls[::2], ls[1::2])))