Swetha H
Swetha H

Reputation: 29

to check a condition for all the items in two list in python

I need to check a condition for all the items in two 1-dimensional lists

For example:

L = [12,23,56,123,13,15]
B = [45,89,12,45,19,89]

For the above two lists, how do I need to check the condition if(L[i] > (float(B[i]*1.1))) where 'i' is the index's starting from index 0 to all the items in the lists (in this case index is 0 to 5).I also need to print the items of list1(L) which fails the condition?

Upvotes: 2

Views: 1047

Answers (3)

glglgl
glglgl

Reputation: 91049

In order to print the ones who are matching, you could use

matching = (l > float(b * 1.1) for l, b in zip(L, B))

This gives you a generator which you can use as you want. E.g.:

for m, l in zip(matching, L):
    if m:
        print l

But you could as well directly generate an iterator of matching ones:

matching = (l for l, b in zip(L, B) if l > float(b * 1.1))

and then print them or just check for emptiness.

Depending on what you want to do, it might be appropriate to change the generator expression to a list comprehension:

matching = [l for l, b in zip(L, B) if l > float(b * 1.1)]

Upvotes: 0

roman
roman

Reputation: 117390

If I understood you right, you can do this with generator expression and zip function

L = [12,23,56,123,13,15]
B = [45,89,12,45,19,89]
all(x[0] > (x[1]*1.1) for x in zip(L, B))

or, as Ashwini Chaudhary suggested in comments, with values unpacking:

L = [12,23,56,123,13,15]
B = [45,89,12,45,19,89]
all(l > (b * 1.1) for l, b in zip(L, B))

To get items from list L which fails the condition:

[l for l, b in zip(L, B) if l <= (b * 1.1)]

Upvotes: 6

Joran Beasley
Joran Beasley

Reputation: 113988

not sure this is what you want but its a cool numpy thing

>>> L = numpy.array(L)
>>> B = numpy.array(B)
>>> B < L
array([False, False,  True,  True, False, False], dtype=bool)
>>> L[L > B* 1.1]
array([ 56, 123])
>>> all(L > B*1.1)

Upvotes: 2

Related Questions