1

Any suggestion how to merge it better so the dual digits numbers does not split? Sorry for bad english.

def merge(strArr):
    newList = []
    for x in range(len(strArr)):
        newList += strArr[x]
    return newList

array_test = ["1, 3, 4, 7, 13", "1, 2, 4, 13, 15"]
print(merge(array_test))

output =['1', ',', ' ', '3', ',', ' ', '4', ',', ' ', '7', ',', ' ', '1', '3', '1', ',', ' ', '2', ',', ' ', '4', ',', ' ', '1', '3', ',', ' ', '1', '5']`

expected output= [1,2,3,4,7,13,1,2,4,13,15]

3
  • What's the expected output? Commented Apr 18, 2020 at 15:21
  • just the numbers Commented Apr 18, 2020 at 15:23
  • because you take each inner string and add each character of each inner string to your return-list. Commented Apr 18, 2020 at 15:28

3 Answers 3

3

Using list comprehension:

merged_arr = [n for s in array_test for n in s.split(", ")]
print(merged_arr)

This prints:

['1', '3', '4', '7', '13', '1', '2', '4', '13', '15']
Sign up to request clarification or add additional context in comments.

Comments

1

It merges this way because for lists += is an array concatenation and that in this context your string object is interpreted as an array of characters:

[] += "Hello"
# Equivalent to 
[] += ["H", "e", "l", "l", "o"]

If you want to join strings you can do:

out = "".join(array_test)

Comments

0

Your result becomes the way it is, because you take each inner string and add each character of it to your return-list without removing any spaces or commas.

You can change your code to:

def merge(strArr):
    new_list = []
    for inner in strArr:
        new_list.extend(inner.split(", "))  # split and extend instead of += (== append)

    return new_list


array_test =["1, 3, 4, 7, 13", "1, 2, 4, 13, 15"]
merged = merge(array_test)
as_int = list(map(int,merged))

print(merged)
print(as_int)

Output:

['1', '3', '4', '7', '13', '1', '2', '4', '13', '15']


[1, 3, 4, 7, 13, 1, 2, 4, 13, 15]

Without as_int()you will still hav strings in your list, you need to convert them into integers.

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.