'How do I split certain element within a list to create another list in python?

I have a list below:

list = [' ab: 1', ' cd: 0', ' ef: 2 gh: 3', ' ik: 4']

From above list, I need something like below:

newlist = [' ab: 1', ' cd: 0', ' ef: 2', ' gh: 3', ' ik: 4']

So "list" contains 4 elements and then I need "newlist" to contain 5 elements.

Is there any way split() can be used here?



Solution 1:[1]

I would approach this by using re.findall in the following way:

import re

li = [' ab: 1', ' cd: 0', ' ef: 2 gh: 3', ' ik: 4']
newlist = []
for ele in li:
    match = re.findall(r"\w+\s?:\s?\d+", ele)
    newlist += [m for m in match]

print(newlist)

Output:

['ab: 1', 'cd: 0', 'ef: 2', 'gh: 3', 'ik: 4']

Solution 2:[2]

Checking method for the best.

list_name = [' ab: 1', ' cd: 0', ' ef: 2 gh: 3', ' ik: 4']
newlist = []
for value in list_name:
    if len(value) > 6:
        newlist.append(value[0:6])
        newlist.append(value[6:])
    else:
        newlist.append(value)
print(newlist)

as you can see, python have a great syntax called slicing (value[0:6])

if you learned about range(start,stop,step) you can use this as well list_name[start:stop:step]

the empty value will automaticaly set into the default [0,-1,1]

have fun :)

Solution 3:[3]

Try this:

newlist = []

for i in a:
    if len(i.split()) != 1:
        for key, val in zip(i.split()[::2], i.split()[1::2]):
            newlist.append(key + val)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 ariamadeus
Solution 3 Edward