Well, let's work through this one step at a time.
As a set of partially-nested for-loops, your code would be:
numbers = []
for ticket in tickets:
numbers.append(re.split(' ?- ?', ticket.text.strip())
flat = []
for setlist in numbers:
for item in setlist:
flat.append(item)
Talking through it:
You have a list of tickets. Each ticket becomes one setlist when you apply the regex split to it. You then want to grab all the items in the setlist and put them in a single list. You don't actually need to have a list of all the setlists (what you called numbers
) at any point - that's just an intermediate stage.
Refactoring this to be completely nested:
flat = []
for ticket in tickets:
for item in re.split(' ?- ?', ticket.text.strip()):
flat.append(item)
Now that we have a set of completely-nested for loops, it's trivial to refactor into a list or generator comprehension:
flat = [item for ticket in tickets for item in re.split(' ?- ?', ticket.text.strip())]
It's a fairly long single line, but it is a single line.
Incidentally, a regex might not be the best way to parse out numbers like that - especially if you want the actual numbers rather than strings. re.split()
is slower than str.split()
, and this split is simple enough that it can be done by the latter. If the numbers are integers, try:
flat = [int(item) for ticket in tickets for item in ticket.split('-'))]
And if they're floats, try:
flat = [float(item) for ticket in tickets for item in ticket.split('-'))]
This works because the int(str)
and float(str)
builtins automatically ignore whitespace at the start and end of a given string, so you don't need a regex to conditionally match that whitespace. The resulting numbers can still be inserted into strings if you need to do that, and should also take up somewhat less space in memory. If the numbers are integers, you lose nothing. If they're floats, you lose very little - you lose the original precision of the number, and you might run into the limits on float size if you're working with really big or really tiny stuff (but that's unlikely - see sys.float_info
for what those limits are).