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,881
  • 4
  • 20
  • 39
BBG_GIS
  • 306
  • 5
  • 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,881
  • 4
  • 20
  • 39
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
  • 13,980
  • 4
  • 22
  • 50
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
  • 12,336
  • 9
  • 27
  • 49