比较列表并获得计数

时间:2018-10-11 01:55:30

标签: python list

我有三个列表

year= [2001, 2002, 2005, 2002, 2004, 2001, 2001, 2002, 2003, 2003, 2002, 2002, 2003, 2004, 2005, 2003, 2004, 2005, 2004, 2004 ]
indviduals= [12, 23, 24, 28,30, 15, 17, 18, 18, 19, 12, 15, 12, 12, 12, 15, 15, 15, 12, 12]
employers= ['a', 'b', 'c', 'd', 'e', 'a', 'a', 'b', 'b', 'c', 'b', 'a', 'c', 'd', 'e', 'a', 'a', 'a', 'a', 'b']

当我运行下面的脚本时,我可以在列表中找到各个员工。我想做的是

a:[12, 15, 17, 15] for 2001年

如果我能做到这一点,我认为得到的只是长度。

for index, item in enumerate(year): 
    for i in np.unique(employers[index]):
        count=0
        #print(i)

        #j=indviduals[index]
        count +=1
        print(i)

2 个答案:

答案 0 :(得分:3)

您可以使用列表理解

查找在雇主列表中匹配元素为“ a”的所有个人

[individuals[i] for i, x in enumerate(employers) if x == 'a']

如果要计算,那么

sum(1 for x in employers if x == 'a') 

否则,我建议使用一个元组列表,您可以更轻松地进行过滤,而不存储并行列表

答案 1 :(得分:1)

为您的所有雇主做什么?使用buitin dict的方法dict.fromkeys

d = dict.fromkeys(employers, ())
cond_year = 2001
for i,e,y in zip(indviduals, employers, year):
    if y == cond_year:
        d[e] = d[e] + (i,)

可打印

{'a': (12, 15, 17), 'b': (), 'c': (), 'd': (), 'e': ()}