list: from 2 to 3 dimensions..looking for a nice way

Robert Brewer fumanchu at amor.org
Sat Nov 29 23:21:41 CET 2003



> -----Original Message-----
> From: sven [mailto:salvadorindali at gmx.de] 
> Sent: Saturday, November 29, 2003 1:52 PM
> To: python-list at python.org
> Subject: list: from 2 to 3 dimensions..looking for a nice way
> 
> 
> 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']]]
> 
> 
> I' achieving this with an ugly syntax:
> 
> a = [[1,'house'],[2,'house'],[3,'garden']]
> b = [[]]
> b[0].append(a.pop(0))
>  
> for id in range(len(a)):
> 	if(b[-1][0][1]==a[id][1]):
> 		b[-1].append(a[id])
> 	else:
> 		b.append([a[id]])
> 
> What is the pythonic way to do this?
> Thanks for any insight
> -- 
> http://mail.python.org/mailman/listinfo/python-list

First, I find it easier to read:

b = [[a.pop(0)]]

than:

b = [[]]
b[0].append(a.pop(0))

Second, anytime you find yourself writing range(len(sequence)), you are
probably doing yourself a disservice. Use something like:

for eachItem in a:
    if(b[-1][0][1]==eachItem[1]):
        b[-1].append(eachItem)
    else:
        b.append([eachItem])

That's "more pythonic" ("Simple is better than complex", etcetera).

But, to me, the "most pythonic" approach would be to ask why you want to
end up with such a structure, instead of, for example:

{'house': [1, 2], 'garden': [3]}

...which comes closer to the Zen ("Flat is better than nested", cf
http://www.awaretek.com/zen.html), and which could be produced with:

b = {}
for eachItem in a:
    index, name = eachItem[0], eachItem[1]
    if name in b:
        b[name].append(index)
    else:
        b[name] = [index]

...although you might want to do a further check when appending to
b[name], to weed out duplicate indices. Depends on the particular
problem.

So why *do* you want a triply-nested list?


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org





More information about the Python-list mailing list