-1

For the following list:

races=['R1', 'R2', 'R3', 'R4', 'R1', 'R2', 'R1', 'R2', 'R3', 'R4', 'R5']

I would like to divide this into:

list_1=['R1', 'R2', 'R3', 'R4']
list_2=['R1', 'R2']
list_3=['R1', 'R2', 'R3', 'R4', 'R5']

So - in using list comprehension with the idea that as soon as the 'R' numbers start descending, a new list starts. My attempt for list_1 is:

list_1=[i for i in races if int(i.split('R')[1])>int((i-1).split('R')[1])]

This doesn't quite work - plus how to handle list_2 and list_3?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

1 Answers1

1

You will make it more complicated if you try to use a list comprehension. An explicit loop enables a simple solution:

races = ['R1', 'R2', 'R3', 'R4', 'R1', 'R2', 'R1', 'R2', 'R3', 'R4', 'R5']

out = []

for r in races:
    if not out or r < out[-1][-1]:
        out.append([])
    out[-1].append(r)

print(out)

Gives:

[['R1', 'R2', 'R3', 'R4'], ['R1', 'R2'], ['R1', 'R2', 'R3', 'R4', 'R5']]

Note that actually splitting to individual variables would require doing some "hacky" operation (such as use of globals or exec). Keep the outputs in a collection, as shown in this example, and index as required.

However, in the special case where the number of output variables is known, you could unpack it:

list_1, list_2, list_3 = out
alani
  • 12,573
  • 2
  • 13
  • 23
  • Alani - thanks very much for this. So - on the first pass through this loop: r = R1 and out[-1][-1] = nothing (nothing in the 'out' list yet).......so confused about: r < out[-1][-1].....to my way of thinking this would throw an error.....but it doesn't. – Angus Stevenson Aug 31 '20 at 09:19
  • @AngusStevenson Look up about short-circuit evaluation of `or` - because `not out` evaluates `True`, the `out[-1][-1]` is never evaluated on that iteration. (Yes it *would* throw an error *if* it were evaluated.) – alani Sep 01 '20 at 20:56
  • @AngusStevenson see e.g. https://realpython.com/python-or-operator/#short-circuit-evaluation – alani Sep 01 '20 at 20:58
  • Thanks a lot Alani - I'll look this up. – Angus Stevenson Sep 03 '20 at 08:15