Home > Back-end >  Checking if values in a list appear in another list
Checking if values in a list appear in another list

Time:03-10

I've got a list with 2 values in it. I want to compare those values against a 3 ranges (lotSize) - each range has a single value associated with it - so ultimately I want to be able to reference this final value when one of the 2 values falls within either of the 5 ranges.

The 2 values to compare:

countList = [150,250]

Currently I have a list for the range values e.g.

lotSize = [{'range': range(100,200), 'finalValue': 10},{'range': range(201,300), 'finalValue': 20},{'range': range(301,400), 'finalValue': 30},]

I have no idea how to go about seeing if the values in countList are in one of the ranges and if true then getting the "finalValue" - I imagine a for loop would be needed here?

CodePudding user response:

You can create a function that maps one entry in countList to a final value, then use map() and list() to repeat this for every element in countList:

def get_final_value(item, lotSize):
    for entry in lotSize:
        if item in entry['range']:
            return entry['finalValue']
    
    raise ValueError(f"{item} is in not any of the ranges")

countList = [150,250]
lotSize = [{'range': range(100,200), 'finalValue': 10},{'range': range(201,300), 'finalValue': 20},{'range': range(301,400), 'finalValue': 30}]

result = list(map(lambda x: get_final_value(x, lotSize), countList))
print(result) # Prints [10, 20]

CodePudding user response:

countList = [150,250]

lotSize = [{'range': range(100,200), 'finalValue': 10},{'range': range(201,300), 'finalValue': 20},{'range': range(301,400), 'finalValue': 30},]

def get_fv(cl):
    fv =[]
    for c in cl:
        for ls in lotSize:
            r = ls['range']
            if c in r:
                fv.append(ls['finalValue'])
    return fv

print(get_fv(countList))                

Output:

[10, 20]

CodePudding user response:

The easiest approach that came to my mind is what follows:

[y["finalValue"] for y in lotSize for x in countList if x in y["range"]]

Output

[10, 20]

But note that, this will results in duplicates if you both countSize values exist in the range key. In this case, you just need to transform it to set and then transform it to list in order to remove the duplicates.

  • Related