[英]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. 当
first_name_baby = S AND age_baby = 1
时实际上有2次,但是我需要为此编写一个Python程序。
Use zip
to combine corresponding list entries and then .count
使用
zip
组合相应的列表条目,然后组合.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. 或者,您可以使用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
you can just take the sum of 1
whenever the conditions match. 只要条件匹配,您就可以取
1
的总和。 iterate over the lists simultaneously using zip
: 使用
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
; 之所以有效,是因为python中的
__str__
是int
子类, True
基本上是1
(重载__str__
和__repr__
), False
是0
; therefore the booleans can just be summed and the result is the number of True
comparisons. 因此,布尔值可以被求和,结果是
True
比较的次数。
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
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.