On Sep 22, 2008, at 11:50 PM, Steve Willoughby wrote:
Dinesh B Vadhia wrote:
Thanks Steve. How do you sort on the second element of each list
to get:
a' = [[42, 'fish'],
[1, 'hello']
[2, 'world']
]
something like this would do the trick:
a_prime = sorted(a, key=(lambda i: i[1]))
sorted(a) returns a new list consisting of the elements in a
but in sorted order. the key= parameter says how to derive the
sort key from any given element; in this case, the elements
being sorted are themselves lists, and element #1 in the sub-list
(a.k.a. "row") is the key.
try itemgetter:
In [1]: a = [[42, 'fish'],
...: [2, 'world'],
...: [1, 'hello']]
In [2]: from operator import itemgetter
In [3]: sorted(a, key=itemgetter(1))
Out[3]: [[42, 'fish'], [1, 'hello'], [2, 'world']]
From: Steve Willoughby Sent: Monday, September 22, 2008 8:16 PM
To: Dinesh B Vadhia Cc: tutor@python.org Subject: Re: [Tutor] array
of different datatypes
Dinesh B Vadhia wrote:
I have looked (honestly!) and cannot see an array structure to
allow different datatypes per column. I need a 2 column array
with column 1 = an integer and column 2 = chars, and after
populating the array, sort on column 2 with column 1 sorted
relatively.
If by "array" you mean a regular Python list, the data type of
every single element may be different. So it's just how lists
always work.
a = [[1, 'hello'],
[2, 'world'],
[42, 'fish'],
]
Thanks!
Dinesh
------------------------------------------------------------------------
_______________________________________________
Tutor maillist - Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
_______________________________________________
Tutor maillist - Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
_______________________________________________
Tutor maillist - Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor