lundi 30 novembre 2015

separate list into smaller list and go through each smaller list python

I have a list like this

results = [1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0]

I want to separate this list, to group items into 4elements together:

size = 4
group_list_4 = [results[i:i+size] for i  in range(0, len(results), size)]
print "List:" , group_list_4

the result of this command is this:

List: [[1, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [1, 0, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1], [1, 0, 0, 0], [1, 0, 0, 0]]

Into each 4-group I have to check where is 1 element so if the first element on a 4group is 1 it return "first" if second return "second" till four. I have a list called lista where I save JSON obj, the condition for record in records: will be executed based on some data that is equal with numbers of lists with 4elements inside list called results , now I want inside this for loop to include the value that is 1 inside one list of 4elements, and next time that for loop will be executed to include the other list inside results list how can i do that, any help?

lista = []
for record in records:
            json_obj = {}
            json_obj['filename'] = filename
            json_obj['value_1_in_list'] =  put element 1 on list
            lista.append(json_obj)

Aucun commentaire:

Enregistrer un commentaire