sorting strings written to files

Max M maxm at mxm.dk
Wed Apr 9 03:54:00 EDT 2003


William Park wrote:
> onefatman <member27857 at dbforums.com> wrote:
> 
>>Can someone help me?
>>
>>I have a small phone directory .dat file that has the entries
>>written to it as strings with three fields in each, separated by \t
>>and ended by \n.
>>
>>e.g.
>>phbook.write("Joe\tNobody\t62907243\n")
>>phbook.write("Daniel\tStevens\t62962328\n")
>>phbook.write("Ellen\tWay\t62910758\n")
>>phbook.write("Jason\tGreig\t62314587\n")
>>
>>it has a function that allows you to write new entries, but i need to
>>know how to sort them by first name, and then by last name when the
>>first names are the same.
> 
> 
> If it's already written to file, then 
>     man sort
> If it's still in Python, then
>     list.sort()


This could give problems:

l = [
     'a\ta',
     'a\tb',
     'a\tc',
     'a\tad',
     'a\tbe',
     'a\tcf',
     'aa\ta',
     'ab\tb',
     'ac\tc',
     'ad\tad',
     'ae\tbe',
     'af\tcf',
]

l.sort()
print l
 >>> ['a\ta', 'a\tad', 'a\tb', 'a\tbe', 'a\tc', 'a\tcf', 'aa\ta',
  'ab\tb', 'ac\tc', 'ad\tad', 'ae\tbe', 'af\tcf']

You would need to split them on the '\t' first.

l = [
     'a\ta',
     'a\tb',
     'a\tc',
     'a\tad',
     'a\tbe',
     'a\tcf',
     'aa\ta',
     'ab\tb',
     'ac\tc',
     'ad\tad',
     'ae\tbe',
     'af\tcf',
]

# decorate sort undecorate
l2 = [i.split('\t')[:2] + [i] for i in l]
l2.sort()
sorted = [i[-1] for i in l2]
print sorted

 >>> ['a\ta', 'a\tad', 'a\tb', 'a\tbe', 'a\tc', 'a\tcf', 'aa\ta',
'ab\tb', 'ac\tc', 'ad\tad', 'ae\tbe', 'af\tcf']

-- 

hilsen/regards Max M Rasmussen, Denmark

http://www.futureport.dk/
Fremtiden, videnskab, skeptiscisme og transhumanisme





More information about the Python-list mailing list