jpcgandre
jpcgandre

Reputation: 1505

Extract rows from list given two criteria

What I have: I have a list of lists, nodes. Each list has the following structure:

nodes = [[ID, number 1, number 2, number 3],[...]]

I also have two other lists of lists called sampleID and sampleID2 where each list may only have single data equal to an ID number which belongs to a subset of the total IDs contained in nodes:

sampleID = [[IDa],[...]]
sampleID2 = [[IDb],[...]], len(sampleID) + len(sampleID2) <= len(nodes)

In some cases these lists can also be like:

sampleID = [[IDa1,IDa2, IDa3,...],[...]]

What I want: Given the above three lists I'd like to obtain in a fast way a fourth list which contains the lists where IDi==ID, i=a,b:

extractedlist = [[ID, number 1, number 2, number 3],[...]], len(extractedlist) = len(sampleID) + len(sampleID2)

My code: Very basic, it works but it takes a lot of time to compute:

import itertools
for line in nodes[:]:
    for line2,line3 in itertools.izip(sampleID[:],sampleID2[:]):
        for i in range(0,len(line2)):
            if line2[i]==line[0]:
                extractedlist.append([line[0], line[1], line[2], line[3]])
        for j in range(0,len(line3)):
            if line3[j]==line[0]:
                extractedlist.append([line[0], line[1], line[2], line[3]])

Upvotes: 0

Views: 64

Answers (1)

Parth Gajjar
Parth Gajjar

Reputation: 1424

I could not understand your problem well but this is what i understand :P

node = [ .... ]
sampleID = [ .... ]
sampleID2 = [ .... ]
final_ids = []
[final_ids.extend(list_item) for list_item in sampleID]
[final_ids.extend(list_item) for list_item in sampleID2]

extractedlist = []

for line in nodes:
    if line[0] in final_ids:
        extractedlist.append(line)

hope this is what you need. Else just add original input-list and result-list in question so i can understand what you want to do :)

Upvotes: 1

Related Questions