我有X个列表,例如:
[potato, pie]
[chicken,chicken,pie,donkey,potato,potato]
我想检查一个术语出现在多少个列表中:
例如:
使用以上两个列表,我希望输出为:
(potato,2)
(pie,2)
(chicken,1) - chicken is only one because it appears only in list two, not in list one.
(donkey,1)
我的尝试,但是我做错了,并且变得困惑,甚至我采取了正确的方法:
x = ['potato', 'pie']
z = ['chicken','chicken','pie','donkey','potato','potato']
list_final = x + z
dict_final = {}
for item in list_final:
if item in dict_final.keys():
dict_final.update({item:(dict_final.get(item) + 1)})
else:
dict_final.update({item:1})
print(dict_final)
我尝试过这个,但这只是计算它出现在列表中的所有时间:
{'potato': 3, 'pie': 2, 'chicken': 2, 'donkey': 1}
但是我想得到:
{'potato': 2, 'pie': 2, 'chicken': 1, 'donkey': 1}
答案 0 :(得分:3)
如果您使其更具功能性)
from collections import Counter
from functools import reduce
x = ['potato', 'pie']
y = ['chicken','chicken','pie','donkey','potato','potato']
all_lists = [x, y]
dict(Counter(reduce(lambda x, y: x + list(set(y)), all_lists, [])).most_common())
# {'potato': 2, 'pie': 2, 'donkey': 1, 'chicken': 1}
答案 1 :(得分:1)
您应该遍历项目列表的set
,以免计数两次。除此之外,您还必须遍历列表中的所有和项:
x = ['potato', 'pie']
z = ['chicken','chicken','pie','donkey','potato','potato']
items = set(x + z)
dict_final = {}
for i in items:
for lst in [x, z]:
if i in lst:
dict_final[i] = dict_final.get(i, 0) + 1
# {'chicken': 1, 'donkey': 1, 'potato': 2, 'pie': 2}
要创建元组列表,您可以
list_final = []
for i in items:
cntr = sum([i in lst for lst in (x, z)])
list_final.append((i, cntr))
...以及对oneliners的粉丝:
list_final = [(i, sum([i in lst for lst in (x, z)])) for i in items]
dict_final = {i: sum([i in lst for lst in (x, z)]) for i in items}
答案 2 :(得分:1)
仅出于兴趣的考虑:这里是目前为止可用的解决方案的时间:
WITH cte AS (
SELECT t.*
, CASE WHEN "IN" IS NOT NULL THEN COUNT("IN") OVER (ORDER BY "TIMESTAMP") END AS rn1
, CASE WHEN "OUT" IS NOT NULL THEN COUNT("OUT") OVER (ORDER BY "TIMESTAMP") END AS rn2
FROM t
)
SELECT cte.*
, LEAD("OUT") OVER (ORDER BY COALESCE(rn1, rn2), rn1 NULLS LAST) AS NEXT_OUT
FROM cte
ORDER BY COALESCE(rn1, rn2), rn1 NULLS LAST
计时代码:
1. double for loop dict : 8.1e-06
2. for loop LC into dict : 1.32e-05
3. LC into LC : 1.37e-05
4. for loop LC into list : 1.41e-05
5. LC into DC : 1.41e-05
6. Counter/reduce : 2.47e-05
7. Counter/reduce into dict: 2.64e-05