lundi 5 mars 2018

cycle through list and keep only relevant elements

Background: I have the following

data = [{'name': 'Jon','id_str': '01'},{'name': 'Tom','id_str': '02'}, {'name': 'Jim','id_str': '03'}] 
id = ['01','1133', '02', '2222']

Goal: Keep data when id == id_str and append to a list.

The code below appends the first data point [{'id_str': '01', 'name': 'Jon'}] (which is what I want)

id_list = [] 
for d in range(len(data)):
    t = data[d]          
    id_str = t['id_str']       

    if id_str == id[d]: 
        keep = data[d]  
        id_list.append(keep)

Problem: Now I want to move onto the next id in the list '1133'. But since the second id value '1133' does not equal the id_str for the second value in data ({'name': 'Tom','id_str': '02'}, I want it to skip this and move on to the third value in id which is '02'. Since id ('02') is equal to id_str ({'name': 'Tom','id_str': '02'}) I want to append.

I want to continue this process and cycle until all of the id = ['01','1133', '02', '2222'] are checked. This website http://love-python.blogspot.com/2012/03/get-next-element-from-list-in-python.html. and suggests that I should add a counter at some point, along with if-else statements but I've tried many times and I'm not sure how.

I would guess my final code would look something like the following

id_list = [] 
for d in range(len(data)):
    t = data[d]          
    id_str = t['id_str']       

    if id_str == id[d]: 
        keep = data[d]  
        id_list.append(keep)

    elif id_str != ID_List[d]: 
         skip 
         check next id
    else:
         if no more id to check
         break

Desired final output:

[{'name': 'Jon','id_str': '01'},{'name': 'Tom','id_str': '02'}] 

Question: How do I accomplish these goals:

1) keep and append desired data (when id == id_str)

2) skip unwanted data (when id != id_str)

3) break when finished cycling through id

Aucun commentaire:

Enregistrer un commentaire