1

I have a long list of strings with the useful data surrounded by empty strings like

['',  '', '1', 'City', '10 (5 | 5)', '7 (3 | 4)', '2 (2 | 0)', '1 (0 | 1)', '24', '9', '15', '23', '', '', '2', 'nal', '10 (5 | 5)', '7 (3 | 4)', '2 (1 | 1)', '1 (1 | 0)', '23', '10', '13', '23', '', '', '3', 'pool', '10 (4 | 6)', '7 (3 | 4)', '2 (1 | 1)', '1 (0 | 1)', '24', '13', '11', '23', '', '',....]

I will like to extract the useful data to a list, for example the first item to extract will be

'1', 'City', '10 (5 | 5)', '7 (3 | 4)', '2 (2 | 0)', '1 (0 | 1)', '24', '9', '15', '23'

the second item to extract will be

 '2', 'nal', '10 (5 | 5)', '7 (3 | 4)', '2 (1 | 1)', '1 (1 | 0)', '23', '10', '13', '23'

and so on

1 Answer 1

3

You can use groupby:

>>> from itertools import groupby
>>> d = ['', '', '1', 'City', '10 (5 | 5)', '7 (3 | 4)', '2 (2 | 0)', '1 (0 | 1)
', '24', '9', '15', '23', '', '', '2', 'nal', '10 (5 | 5)', '7 (3 | 4)', '2 (1 |
 1)', '1 (1 | 0)', '23', '10', '13', '23', '', '', '3', 'pool', '10 (4 | 6)', '7
 (3 | 4)', '2 (1 | 1)', '1 (0 | 1)', '24', '13', '11', '23', '', '']
>>> [list(g) for k, g in groupby(d, bool) if k]
[['1', 'City', '10 (5 | 5)', '7 (3 | 4)', '2 (2 | 0)', '1 (0 | 1)', '24', '9', '
15', '23'], ['2', 'nal', '10 (5 | 5)', '7 (3 | 4)', '2 (1 | 1)', '1 (1 | 0)', '2
3', '10', '13', '23'], ['3', 'pool', '10 (4 | 6)', '7 (3 | 4)', '2 (1 | 1)', '1
(0 | 1)', '24', '13', '11', '23']]

groupby groups the consecutive elements in the iterable based on the key function given as a second parameter. For each resulting group it returns tuple consisting of key value and iterator over the elements in the group.

In above bool is used as key function and it returns True for non-empty strings and False for empty ones. Then the final result is generated by discarding the groups with False key and converting the iterables to lists so that output can be printed.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @niemmi, Nice. That worked out pretty well, though I have no idea what went down. Can you spare a few mins to explain the list comprehension?
@MokogwuChiedu Added explanation, hope it helps!
Thanks, I get it now

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.