Home > database >  Python: Find count of elements of one list when condition in another list is fulfilled
Python: Find count of elements of one list when condition in another list is fulfilled

Time:01-13

Let's say I have two lists list1 and list2 as:

list1 = [ 3, 26, 17, 7, 35, 8, 14, 24 ]

list2 = [ long, long, long, short, short, short, short, short ]

I want to find the count of 'short' of list2 when elements in list1 > 10.

Expected output is 3, as 35, 14, 24 in list1 are > 10. and they corresponds to "short' in list 2.

CodePudding user response:

If you want to treat these two lists as a list of pairs, you can zip them together, with something like the following.

Note that I'm using the sum function here to count the number of times the expression evaluates to True (with True automatically treated as 1 and False as 0).

# Assuming that `long` and `short` are arbitrary objects
long = object()
short = object()

list1 = [3, 26, 17, 7, 35, 8, 14, 24]
list2 = [long, long, long, short, short, short, short, short]

print(sum(num > 10 and category is short
          for num, category in zip(list1, list2)))

CodePudding user response:

Length of both the lists should be same then only you can apply corresponding element condition.

c=0  #counter variable
list1 = [ 3, 26, 17, 7, 35, 8, 14, 24 ]
list2 = ['long','long','long','short','short','short','short','short']

for x,y in enumerate(list2):   #you can track the position and value with enumerate
    if y=='short' and list1[x]>10:
       c =1
print(c)
#3

You can also do in one line with sum and generator expression

sum(1 for x,y in enumerate(list2) if y=='short' and  list1[x]>10)
#3

CodePudding user response:

You can use zip to iterate over both lists at the same time and increment a counter if a condition is met:

count=0
for x, y in zip(list1, list2):
    if x>10 and y=="short":
        count =1

Keep in mind it will iterate until it reaches the end of the shorter iterable.

CodePudding user response:

When used in an arithmetic context, True and False have effective values of 1 and 0 respectively. Therefore:

list1 = [ 3, 26, 17, 7, 35, 8, 14, 24 ]
list2 = ['long','long','long','short','short','short','short','short']

print(sum(x > 10 and y == 'short' for x, y in zip(list1, list2)))

Output:

3
  • Related