I have an array like so: ['A', 'B', 'C', 'D', 'E'].
I've been trying to figure out how to make it like so: ['AB', 'CD', 'E']
I'm not sure where to start. Thanks in advance!
main.py
a = ['A', 'B', 'C', 'D', 'E']
b = [i + j for i, j in zip(a[:-1:2], a[1::2])]
if len(a) % 2 == 1:
b.append(a[-1])
print(b)
result
$ python main.py
['AB', 'CD', 'E']
zip(a[::2], a[1::2] + ['']), although it's less efficient.>>> [''.join(a[i:i+2]) for i in range(0, len(a), 2)]
['AB', 'CD', 'E']
or (as I love iterators)
>>> it = iter(a)
>>> [s + next(it, '') for s in it]
['AB', 'CD', 'E']
I think that the easier way is to iterate through the array and concatenate the chars, it works if you have an array with even length, so you could add a check and append the last element in case of odd length.
array = ['A', 'B', 'C', 'D', 'E']
array2 = [f"{array[i]}{array[i+1]}" for i in range(0, len(array)-1, 2)]
if len(array)%2!=0:
array2.append(array[-1])
print(array2)
Try like this. This is very bare answer but should work.
my_array = ['A', 'B', 'C', 'D', 'E']
def combine_array(my_array):
mixed_array = []
start_new = True
for item in my_array:
if start_new:
mixed_array.append(item)
start_new = False
else:
mixed_array[-1] = mixed_array[-1] + item
start_new = True
return mixed_array
if __name__ == "__main__":
try:
print(combine_array(my_array))
except Exception as err:
print(err)
for n in range(0,len(array)): newarray[n//2] += array[n]grouperrecipe from theitertoolsdocumentation provides a decent solution