Mike
Mike

Reputation: 1

Compare different elements in two different lists

I need to compare if 2 different data are matching from different lists.

I have those 2 lists and I need to count the numbers of babies with :

first_name_baby = S AND age_baby = 1 
age_baby = [ 2, 1, 3, 1, 4, 2, 4, 1, 1, 3, 4, 2, 2, 3].  first_name_baby= [ T, S, R, T, O, A, L, S, F, S, Z, U, S, P]

There is actually 2 times when first_name_baby = S AND age_baby = 1 but I need to write a Python program for that.

Upvotes: 0

Views: 74

Answers (4)

vash_the_stampede
vash_the_stampede

Reputation: 4606

x = len([item for idx, item in enumerate(age_baby) if item == 1 and first_name_baby[idx] == 'S'])
2

Expanded:

l = []
for idx, item in enumerate(age_baby):
    if item == 1 and first_name_baby[idx] == 'S':
        l.append(item)
x = len(l)

Upvotes: 0

hiro protagonist
hiro protagonist

Reputation: 46849

you can just take the sum of 1 whenever the conditions match. iterate over the lists simultaneously using zip:

# need to make sense of the names
T, S, R, O, A, L, F, Z, U, S, P = 'T, S, R, O, A, L, F, Z, U, S, P'.split(', ')
age_baby = [2, 1, 3, 1, 4, 2, 4, 1, 1, 3, 4, 2, 2, 3]
first_name_baby = [T, S, R, T, O, A, L, S, F, S, Z, U, S, P]


sum(1 for age, name in zip(age_baby, first_name_baby) 
    if age == 1 and name == S)

thanks to Austin a more elegant version of this:

sum(age == 1 and name == S for age, name in zip(age_baby, first_name_baby))

this works because bools in python are subclasses of int and True is basically 1 (with overloaded __str__ and __repr__) and False is 0; therefore the booleans can just be summed and the result is the number of True comparisons.

Upvotes: 1

Paul Panzer
Paul Panzer

Reputation: 53029

Use zip to combine corresponding list entries and then .count

>>> age_baby = [ 2, 1, 3, 1, 4, 2, 4, 1, 1, 3, 4, 2, 2, 3]
>>> first_name_baby = "T, S, R, T, O, A, L, S, F, S, Z, U, S, P".split(', ')
>>> list(zip(first_name_baby, age_baby)).count(('S', 1))
2

Alternatively, you could use numpy. This would allow a solution very similar to what you have tried:

>>> import numpy as np
>>>                                                                                                             
>>> age_baby = np.array(age_baby)                                                    
>>> first_name_baby = np.array(first_name_baby)                                      
>>>                                                                                                                 
>>> np.count_nonzero((first_name_baby == 'S') & (age_baby == 1))                                      
2

Upvotes: 2

jagath
jagath

Reputation: 238

Try this:

>>> count = 0
>>> 
>>> 
>>> for i in range(len(first_name_baby)):
...   if first_name_baby[i] == 'S' and age_baby[i] == 1:
...     count += 1
... 
>>> count
2

Upvotes: 0

Related Questions