Reputation: 406
So essentially what I'm doing is making a shipyard class that has the attribute "_containers" which is a singly linked list of container objects. Each container has the attribute "_destination" which is where it's going.
The shipyard._containers list has to be arranged alphabetically by destination. I know how to accomplish all of this except comparing the two destinations.
How can I compare two strings and figure out which one goes first based on alphabetical order? I'm not allowed to use any python lists at all.
Upvotes: 0
Views: 279
Reputation: 16711
containers = sorted(containers, key = lambda i: i.desitination)
Upvotes: 0
Reputation: 881695
When x
and y
are variables naming Python objects that are strings,
x < y
is True
if and only if x
is alphabetically before y
.
This may or may not match what you mean by "alphabetically before". For example, all uppercase characters do come alphabetically before lowercase ones, so if x='Zebra'
and y='aardvark'
, x < y
will be True
. To specifically ignore upper/lower case distinctions, use
x.lower() < y.lower()
More generally, Unicode can present several such traps, whereby code points that are in a certain order do not mean they must be compared in that order. For a completely general approach to the Unicode Collation Algorithm, you can look at various alternatives discussed at How do I sort unicode strings alphabetically in Python? .
Upvotes: 3