What would be an elegant way to represent an arbitrary total order between elements of a list in Python, e.g. the function torder in the following example (where C>B>A). Edit: I assume the list defines the order:
>>> s = ['A','B','C']
>>> torder('B')
['A']
>>> torder('C')
['A','B']
I could do that using if and elif if the list is short but was looking for something more pythonic.
def orde(i, s):
t = sorted(s)
return t[:t.index(i)]
s = ['A','B','C']
orde("B", s)
import itertools
itertools.takewhile(lambda x: x != 'C', s)
If order is not defined by the position in the list:
sorted(filter(lambda x: x < 'C', s))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With