pythonic way to sort
Boris Borcic
bborcic at gmail.com
Thu May 4 04:35:42 EDT 2006
Jay Parlar wrote:
>
> On May 4, 2006, at 12:12 AM, micklee74 at hotmail.com wrote:
> [...]
> Assume that you have the lines in a list called 'lines',
> as follows:
>
> lines = [
> "1SOME STRING ~ABC~12311232432D~20060401~00000000",
> "3SOME STRING ~ACD~14353453554G~20060401~00000000",
> "2SOME STRING ~DEF~13534534543C~20060401~00000000"]
>
>
> The more traditional way would be to define your own comparison function:
>
> def my_cmp(x,y):
> return cmp( x.split("~")[1], y.split("~")[1])
>
> lines.sort(cmp=my_cmp)
>
>
> The newer, faster way, would be to define your own key function:
>
> def my_key(x):
> return x.split("~")[1]
>
> lines.sort(key=my_key)
and if the data is in a file rather than a list, you may write eg
lines = sorted(file("/path/tofile"),key=mike)
to create it sorted.
More information about the Python-list
mailing list