比较列表并获取

2024-06-17 13:36:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有三张单子

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]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)

Tags: in脚本列表forindexcount员工item
2条回答

你可以用列表理解

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

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

如果你想数一数

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

否则,我建议使用一个元组列表,这样可以更容易地进行筛选,而不是存储并行列表

为你所有的雇主做这件事怎么样?使用内置dict的方法^{}

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': ()}

相关问题 更多 >