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

3 Answers 3

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']]]
Sign up to request clarification or add additional context in comments.

1 Comment

There are some useless spaces, you should remove them as the OP doesn't want them
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(' - '),)]

Comments

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.