0

How to optimize this list result?

I have the following list: rows= ['Azuay', '10,658', '195', '12', 'Bolívar', '2,111', '66', '12', 'Cañar', '2,110', '83', '7', 'Carchi', '3,053', '104', '1', 'Chimborazo', '2,516', '315', '119', 'Cotopaxi', '4,575', '281', '61', 'El Oro', '6,477', '466', '185', 'Esmeraldas', '4,271', '216', '51', 'Galápagos', '227', '1', '1', 'Guayas', '22,263', '1,737', '1,651', 'Imbabura', '4,773', '170', '7', 'Loja', '6,227', '222', '44', 'Los Ríos', '4,017', '342', '237', 'Manabí', '11,284', '1,025', '1,033', 'Morona Santiago', '3,008', '22', '0', 'Napo', '1,440', '74', '2', 'Orellana', '1,956', '53', '17', 'Pastaza', '2,258', '60', '15', 'Pichincha', '59,477', '1,789', '242', 'Santa Elena', '1,738', '368', '274', 'Santo Domingo de los Tsáchilas', '5,293', '361', '116', 'Sucumbíos', '2,763', '92', '2', 'Tungurahua', '5,119', '276', '223', 'Zamora Chinchipe', '1,580', '53', '1'] I want to convert it to : [['Azuay', '10,658', '195', '12'], ['Bolívar', '2,111', '66', '12'], ['Cañar', '2,110', '83', '7'], ['Carchi', '3,053', '104', '1'], ['Chimborazo', '2,516', '315', '119'], ['Cotopaxi', '4,575', '281', '61'], ['Esmeraldas', '4,271', '216', '51'], ['Galápagos', '227', '1', '1'], ['Guayas', '22,263', '1,737', '1,651'], ['Imbabura', '4,773', '170', '7'], ['Loja', '6,227', '222', '44'], ['Manabí', '11,284', '1,025', '1,033'], ['Napo', '1,440', '74', '2'], ['Orellana', '1,956', '53', '17'], ['Pastaza', '2,258', '60', '15'], ['Pichincha', '59,477', '1,789', '242'], ['Sucumbíos', '2,763', '92', '2'], ['Tungurahua', '5,119', '276', '223'], ['Zamora Chinchipe', '1,580', '53', '1']] I am using this code to obtain this result; however, I want to optimize it. dict_kv=[] for i in range(0, len(rows)): if (rows[i].strip().isalpha()): dict_kv.append([rows[i],rows[i+1],rows[i+2],rows[i+3]]) dict_kv.append([rows[92],rows[93],rows[94],rows[95]]) # This shouldn't be used pprint(dict_kv) P.D: Can anyone hel me?

2nd Nov 2020, 3:44 AM
Rosana Rodríguez Milanés
Rosana Rodríguez Milanés - avatar
3 Respostas
+ 2
You can write dict_kv = [list(x) for x in zip(*[iter(rows)]*4)] to split rows into chunks of 4
2nd Nov 2020, 4:32 AM
Volodymyr Chelnokov
Volodymyr Chelnokov - avatar
0
Thank you @Volodymyr Chelnokov
2nd Nov 2020, 7:21 PM
Rosana Rodríguez Milanés
Rosana Rodríguez Milanés - avatar