0

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!

3

5 Answers 5

2

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']
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you I figured it out the question. Fixed and updated.
Thank you for check. fixed but your answer is much better for reading and computational efficiency
You could make yours perhaps a bit prettier with zip(a[::2], a[1::2] + ['']), although it's less efficient.
1
>>> [''.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']

1 Comment

Wow, Thanks a ton! I really appreciate it
0

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)

Comments

0

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)

2 Comments

Can someone explain why I got minus ?! This answer is tested and its working.
Maybe someone didn't like the amount of code. I don't like that, either, but it's correct, efficient and simple, so I countervoted.
-1
startArray = ['A', 'B', 'C', 'D', 'E']
currentIndex = 0
finishArray = ['']
for x in startArray:
    if len(finishArray[currentIndex]) == 2:
        currentIndex += 1
        finishArray.insert(currentIndex,x)
    else: 
        finishArray[currentIndex] += x
print(finishArray)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.