简体   繁体   中英

How to split a string with specific character with python in a nested list?

I have a nested list with some strings. I want to split strings with '-' character in an odd interval, as myresult showed. I've seen this question . But it couldn't help me.

mylist= [['1 - 2 - 3 - 4 - 5 - 6'],['1 - 2 - 3 - 4']]

myresult = [[['1 - 2'] , ['3 - 4'] , ['5 - 6']],[['1 - 2] ,[ 3 - 4']]]

Try this:

res = []
for x in mylist:
    data = list(map(str.strip, x[0].split('-')))
    res.append([[' - '.join(data[y * 2: (y + 1) * 2])] for y in range(0, len(data) // 2)])
print(res)

Output:

[[['1 - 2'], ['3 - 4'], ['5 - 6']], [['1 - 2'], ['3 - 4']]]

In case you prefer a one line solution, here it is!

res = [[[s] for s in map(' - '.join,
                         map(lambda x: map(str, x),
                             zip(x[::2], x[1::2])))]
       for lst in mylist for x in (lst[0].split(' - '),)]

list comprehension:

[[[" - ".join(item)] for item in zip(*[iter(sub.split(" - "))]*2)] for l in mylist for sub in l]

Did some changes from How does zip(*[iter(s)]*n) work in Python?

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