Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if elements in list 'a' meet conditions in list 'b'?

I have a list of numbers:

a = [3, 6, 20, 24, 36, 92, 130]

And a list of conditions:

b = ["2", "5", "20", "range(50,100)", ">120"]

I want to check if a number in 'a' meets one of the conditions in 'b' and if yes, put these numbers in list 'c'

In above case:

c = [20, 92, 130]

I created this code what seems to do what I want:

c = []
for x in a:
    for y in b:
        if "range" in y:
            rangelist = list(eval(y))
            if x in rangelist:
                c.append(x)
        elif ">" in y or "<" in y:
            if eval(str(x) + y):
                c.append(x)
        else:
            if x == eval(y):
                c.append(x)

However my list 'a' can be very big.
Is there not an easier and faster way to obtain what I want?

like image 387
Reman Avatar asked Nov 26 '17 08:11

Reman


People also ask

How do you check if all elements of a list match a condition?

Use the any() function to check if any element in a list meets a condition, e.g. if any(item > 10 for item in my_list): . The any function will return True if any element in the list meets the condition and False otherwise.

How do you check if an element in a list is present in another list in Python?

We can use the in-built python List method, count(), to check if the passed element exists in the List.

How do you check if a list contains a particular item?

Elements can be checked from a list using indexOf() or contains() methods.

How do you check if a condition is true for all elements in list python?

The all() function returns True if all items in an iterable are true, otherwise it returns False. If the iterable object is empty, the all() function also returns True.


1 Answers

Building on @user2357112's suggestion, you can create a list of functions for all your conditions, then pass each number, to each function to determine whether the number meets any of the conditions, or not.

In [1]: a = [3, 6, 20, 24, 36, 92, 130]

In [2]: conditions = [lambda x:x==2, lambda x:x==5, lambda x:x==20, lambda x: x in range(50, 100), lambda x: x > 120]  # List of lambda functions

In [3]: output = list()

In [4]: for number in a:
   ...:     if any(func(number) for func in conditions): # Check if the number satisfies any of the given conditions by passing the number as an argument to each function
   ...:         output.append(number)         

In [5]: output
Out[5]: [20, 92, 130]
like image 66
GaneshTata Avatar answered Sep 30 '22 19:09

GaneshTata