list: from 2 to 3 dimensions..looking for a nice way
Peter Otten
__peter__ at web.de
Sat Nov 29 17:23:42 EST 2003
Peter Otten wrote:
> sven wrote:
>
>> I've got a nested list->
>> a = [[1,'house'],[2,'house'],[3,'garden']]
>>
>>
>> and I want to get one level deeper with the lists having the same value
>> in index value 1
>>
>> b =[[[1, 'house'], [2, 'house']], [[3, 'garten']]]
>
>
> How about:
>
> a = [[1,'house'],[2,'house'],[3,'garden']]
>
> d = {}
> for n, s in a:
> d.setdefault(s,[]).append(n)
>
> b = [[[n, s] for n in nlist] for s, nlist in d.iteritems()]
> print b
Or rather
a = [[1,'house'],[2,'house'],[3,'garden']]
d = {}
for ns in a:
d.setdefault(ns[1], []).append(n)
b = d.items()
Peter
More information about the Python-list
mailing list