Home > Enterprise >  How do I split certain element within a list to create another list in python?
How do I split certain element within a list to create another list in python?

Time:05-12

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?

CodePudding user response:

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']

CodePudding user response:

Try this:

newlist = []

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

CodePudding user response:

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 :)

  • Related