alc
alc

Reputation: 309

Get elements of a sublist in python based on indexes of a different list

I have two lists of lists.

I want to get the elements from second list of lists, based on a value from the first list of lists.

I if I have simple lists, everything go smooth, but once I have list of list, I'm missing something at the end.

Here is the code working for two lists (N = names, and V = values):

N = ['name 1', 'name 2','name 3','name 4','name 5','name 6','name 7','name 8','name 9','name 10']

V = ['val 1', 'val 2','val 3','val 4','val 5','val 6','val 7','val 8','val 9','val 10']

bool_ls = []
NN = N
for i in NN:
        if i == 'name 5':
            i = 'y'
        else:
            i = 'n'
        bool_ls.append(i)

# GOOD INDEXES = GI

GI = [i for i, x in enumerate(bool_ls) if x == 'y']

# SELECT THE GOOD VALUES = "GV" FROM V

GV = [V[index] for index in GI]

if I define a function, works well applied to the two lists:

def GV(N,V,name):
    bool_ls = []
    NN = N
    for i in NN:
        if i == name:
            i = 'y'
        else:
            i = 'n'
        bool_ls.append(i)
    GI = [i for i, x in enumerate(bool_ls) if x == 'y']
    GV = [V[index] for index in GI]

    return GV 

Once I try "list of list", I cannot get the similar results. My code looks like below so far:

NN = [['name 1', 'name 2','name 3'], ['name 1', 'name 2','name 3'], ['name 1', 'name 2','name 3'], ['name 1', 'name 2','name 3'], ['name 1', 'name 2','name 3'], ['name 1', 'name 2','name 3']]

VV = [['val 1', 'val 2', 'val 3'], ['val 1', 'val 2', 'val 3'], ['val 1', 'val 2', 'val 3'], ['val 1', 'val 2', 'val 3'], ['val 1', 'val 2', 'val 3']]


def GV(NN,VV,name):
    bool_ls = []
    NNN = NN
    for j in NNN:
        for i in j:
            if i == name:
                i = 'y'
            else:
                i = 'n'
            bool_ls.append(i) 

# here is where I'm lost

Help greatly appreciated! Thank you.

Upvotes: 0

Views: 70

Answers (2)

Moses Koledoye
Moses Koledoye

Reputation: 78546

You can generate pair-wise combinations from both list using zip and then filter in a list comprehension.

For the flat lists:

def GV(N, V, name):
    return [j for i, j in zip(N, V) if i==name]

For the nested lists, you'll add an extra nesting:

def GV(NN,VV,name):
    return [j for tup in zip(NN, VV) for i, j in zip(*tup) if i==name]

In case you want a list of lists, you can move the nesting into new lists inside the parent comprehension.

Upvotes: 2

jeffknupp
jeffknupp

Reputation: 6254

There's an easier way to do what your function is doing, but, to answer your question, you just need two loops (one for each level of lists): the first list iterates over the list of lists, the second iterates over the inner lists and does the somewhat odd y or n thing to chose a value.

Upvotes: 0

Related Questions