迭代2个列表并检查值

时间:2016-02-02 15:51:58

标签: python list

我希望看到值x是否存在于列表的值y中,如果它们存在,我想打印出这些值的总数。

z=0
for x,y in zip(labels,n):
    if x in y:
        z=z+1
print(z)

这就是标签的样子:

[['20011', '20048'],
 ['20011', '20048'],
 ['20011', '20048'],
 ['20011', '20048']]

这就是 n 的样子:

['20011', '20048' ,'20011', '20048']

打印z时我得零。我究竟做错了什么?如果我没有定义z,我会收到一条错误,说明没有定义z。

2 个答案:

答案 0 :(得分:2)

如果您希望计算元素出现在任何位置,请获取所有子列表的并集,并查看l2中每个元素出现的次数:

l = [['20011', '20048'],
 ['20011', '20048'],
 ['20011', '20048'],
 ['20011', '20048']]


l2 = ['20011', '20048' ,'20011', '20048']
union = set.union(*map(set,l))
print(sum(ele in union for ele in l2)) # ->  4

如果您不想多次计算唯一元素,请获取交集:

l = [['20011', '20048'],
     ['20011', '20048'],
     ['20011', '20048'],
     ['20011', '20048']]

l2 = ['20011', '20048', '20011', '20048']
inter = set.union(*map(set, l)).intersection(l2)

print(len(inter)) # ->  2

如果要使用子列表中的元素进行计数:

l = [['20011', '20048'],
     ['20011', '20048'],
     ['20011', '20048'],
     ['20011', '20048']]

l2 = ['20011', '20048', '20011', '20048']
st = set(l2)
from itertools import chain
print(sum(ele in st for ele in chain.from_iterable(l)))

要根据n不相交的子列表进行计数,您可以使用set.isdisjoint,因此如果有任何共同元素not st.isdisjoint(sub)将为True:

l = [['20011', '20048'],
     ['20011', '20048'],
     ['20011', '20048'],
     ['20011', '20048']]

l2 = ['20011', '20048', '20011', '20048']
st = set(l2)
print(sum(not st.isdisjoint(sub) for sub in l)) # -> 4

答案 1 :(得分:1)

numpy.intersect1d可以获得2个数组之间的交集,然后你可以使用size来获取两个数组中唯一元素的数量:

import numpy as np
labels = np.array([[20011,20048],[20011,20048],[20011,20048],[20011,20048]])
n = np.array([20011,20048,20011,20048])
z = np.intersect1d(n,labels).size
print z # counts 2

numpy.in1d可以检查一维数组的每个元素是否在第二个数组中,然后转换为列表并计算True项(不是唯一元素):

z = np.in1d(n,labels).tolist().count(True)
print z # counts 4