简体   繁体   中英

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?

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

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM