1

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']]]
deadshot
  • 8,317
  • 4
  • 15
  • 36
BBG_GIS
  • 296
  • 3
  • 17

3 Answers3

3

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']]]
deadshot
  • 8,317
  • 4
  • 15
  • 36
1

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(' - '),)]
Riccardo Bucco
  • 11,231
  • 3
  • 17
  • 42
1

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?

jizhihaoSAMA
  • 11,804
  • 9
  • 23
  • 43