Kernel.Panic Kernel.Panic - 3 months ago 9
Python Question

How can I generate a list and flatten it the same time in python?

This is more of a refactoring question, as the code works as is. But since I am still learning

Python
, I thought there would be a better way to do this, and I spent a few hours now digging into the other possibilities, but can't get anywhere.

So I have the following statement:

numbers = [re.split(' ?- ?', ticket.text.strip()) for ticket in tickets]


which obviously generates a list of lists. However, I want to have just a single list of the numbers taken out from that regex.

So this is the second line of code that flattens the above list (I found this solution here, on
StackOverflow
btw):

flat = [item for setlist in numbers for item in setlist]


Main thing I am trying to achieve is to have this on 1 single line. Otherwise, I could of course have a normal
for .. in
loop, that would append each number to numbers list, but I like keeping it on 1 line.

If this is the best it can get, I would also love to know that please.. :)

Answer

You can achieve it using chain and map in single line as:

list(chain(*map(lambda x: re.split(' ?- ?', x.text.strip()), tickets)))

Suggestion:

There is no need to use regex here, because you may achieve the same using split function of Python. Hence, your answer will become:

list(chain(*map(lambda x: x.text.replace(' ', '').split('-')), tickets)))

Explaination:

chain function from the itertools library is used to umwrap the list. Below is the sample example

>>> from itertools import chain
>>> my_nested_list = [[1,2,3], [4,5,6]]
>>> list(chain(*my_nested_list))
[1, 2, 3, 4, 5, 6]

Whereas map function is used to call the passed function (in this case lambda function) on each item of list.

>>> my_nested_list = [[1,2,3], [4,5,6]]
>>> map(lambda x: x[0], my_nested_list)
[1, 4]

And, split is used to split the content of string based on substring. For example:

>>> x = 'hey you - i am here'
>>> x.split('-')
['hey you ', ' i am here']  # Same answer as your regex