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?
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.
We can use the in-built python List method, count(), to check if the passed element exists in the List.
Elements can be checked from a list using indexOf() or contains() methods.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With