[Tutor] question on lists

Gregor Lingl glingl@aon.at
Sun, 08 Sep 2002 14:06:08 +0200


Martin Klaffenboeck schrieb:

>Am Sa, 2002-09-07 um 23.33 schrieb Sean 'Shaleh' Perry:
>
>  
>
>>list.sort() takes a function to determine sort order.  There is a handy 
>>function called cmp() which is often used for this.
>>
>>Your add function is not too hard to write and the random module may give you 
>>what you want for the random stuff.
>>    
>>
>
>Ok, that works good with 
>
>for x in words:
>	if x[0] < newword:
>		continue
>	if x[0] > newword:
>		break
>
>	pos = words.index(x)
>
>But what can I do that the words are sorted case insensitive. (No matter
>about upper and lower case letters)?
>
 >>> l = [["Hans",1,2,3],
         ["fritz",4,5,6],
         ["Adam",7,8,9]]
 >>> t = l[:]
 >>> t.sort()
 >>> t
[['Adam', 7, 8, 9], ['Hans', 1, 2, 3], ['fritz', 4, 5, 6]]
 >>> cmp("Adam","Hans")
-1
 >>> cmp("Hans","fritz")
-1
 >>> cmp("Hans".upper(),"fritz".upper())
1
 >>> def vgl(a,b):
    return cmp(a[0].upper(), b[0].upper())

 >>> t = l[:]
 >>> t
[['Hans', 1, 2, 3], ['fritz', 4, 5, 6], ['Adam', 7, 8, 9]]
 >>> t.sort(vgl)
 >>> t
[['Adam', 7, 8, 9], ['fritz', 4, 5, 6], ['Hans', 1, 2, 3]]
 >>>

> 
>And how can I tell words.sort() that it should only sort the first
>column of my 4 column list?
>  
>
What do you mean exactly. Do you want the result for the list
used above to be:
[['Adam', 1, 2, 3], ['fritz', 4, 5, 6], ['Hans', 7, 8, 9]]
???

Gregor

>Martin
>
>  
>