简体   繁体   中英

Sort strings into alphabetical order Python

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.

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? .

containers = sorted(containers, key = lambda i: i.desitination)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM