user14655550
user14655550

Reputation:

splitting a string containing characters

I have the following string:

test = ['2*0', '4' , '3' , '2' , '3*8' , '4' , '5' , '6' ]

I am looking for a way to change the string to the below one:

final = ['0' , '0' , '4' , '3' , '2' , '8' , '8' , '8' , '4' , '5' , '6' ]

I dont know where to start with this one. do I need first to split those elements containing * and create a new string? any suggestions?

Upvotes: 0

Views: 85

Answers (5)

Raghav Gupta
Raghav Gupta

Reputation: 464

Use this simple technique :

final=[]
for i in test:
    if "*" in i:
        a=[i.split("*")[1]]*int(i.split("*")[0])
        final.extend(a)
    else:
        final.append(i)

Upvotes: 0

mujjiga
mujjiga

Reputation: 16856

One liner

[item for sublist in 
 [[s.split("*")[1]]*int(s.split("*")[0]) if "*" in s else s for s in test] 
 for item in sublist]

Upvotes: 1

sahasrara62
sahasrara62

Reputation: 11228

test = ['2*0', '4' , '3' , '2' , '3*8' , '4' , '5' , '6' ]
res = []
for i in test:
    if '*' in i:
            a,b = i.split('*')
            res.extend([b for i in range(int(a))])
    else:
            res.append(i)
# ['0', '0', '4', '3', '2', '8', '8', '8', '4', '5', '6']

Upvotes: 0

Barmar
Barmar

Reputation: 780688

Loop over the list. When there's * in the element, split it and append the second element into the result the appropriate number of times.

def expand_list(l):
    result = []
    for s in l:
        if '*' in s:
            len, val = s.split('*')
            result.extend([val] * int(len))
        else:
            result.append(s)
    return result

Upvotes: 0

Cory Kramer
Cory Kramer

Reputation: 117856

If you find a '*' character, you can str.split on that, and pick apart the value and the number of times to repeat it. Then use itertools.chain.from_iterable to flatten the results into a list.

import itertools

def create_element(s):
    if '*' in s:
        rep, val = s.split('*')
        return [val for _ in range(int(rep))]
    return [s]

list(itertools.chain.from_iterable(create_element(i) for i in test))

Output

['0', '0', '4', '3', '2', '8', '8', '8', '4', '5', '6']

Upvotes: 1

Related Questions