Le Fri, 9 Jan 2009 08:10:27 -0800 (PST), culpritNr1 <ig2ar-s...@yahoo.co.uk> a écrit :
> > Hello Denis and All, > > Your solution does show elegance. To remind people, it's this one: > > lol = [[1,2,3],[4,5,6],[7,8,9]] > new_lol = [[a,b**3,c] for [a,b,c] in lol] > print lol > print new_lol > ==> > [[1, 2, 3], [4, 5, 6], [7, 8, 9]] > [[1, 8, 3], [4, 125, 6], [7, 512, 9]] > > Now, as I said in my original post, I can't assume that all inner-lists will > have the same number of elements. Common data looks like this > > LoL = [['chrX', '160944034', '160944035', 'gnfX.145.788', '63.60'], > ['chrX', '161109992', '161109993', 'rs13484104', '63.60'], > ['chrX', '161414112', '161414113', 'undetermined'], > ['chrX', '161544071', '161544072', 'rs13484106', '63.60', > 'RNA-BP', 'PLoS Biol 6(10): e255'], > ['chrX', '162030736', '162030737', 'gnfX.146.867', '67.05'], > ['chrX', '164171913', '164171914', 'gnfX.148.995', '70.45']] > > Do you still think that this problem can be elegantly tackled by list > comprehensions? The straightforward method is indeed to to loop with neccsary checks/trials embedded in loop. Now, there imo is more elegant method which is to define a custom int that integrates such tests. And then to call this custom conversion instead of built-in int. This lets open the possibility of a list comp expression. Below an example: def possible_cube(val): try: return val ** 3 except: return val lol = [[1,2,'x'],[4,'y',6],['z',8,9]] new_lol = [[possible_cube(val) for val in l] for l in lol] print lol print new_lol ==> [[1, 2, 'x'], [4, 'y', 6], ['z', 8, 9]] [[1, 8, 'x'], [64, 'y', 216], ['z', 512, 729]] This may be longer because there is a custom function call in each loop. Now, it's a question of taste and priority. denis ------ la vida e estranya _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor