我有这样一本字典:
{4722: "['children', 'dance', 'education','technology', 'teaching']",
3200: "['alternative energy', 'sustainability', 'technology']",
1636: "['computers', 'performance', 'simplicity', 'software', 'ice']",
1697: "['MacArthur grant', 'inequality', 'technology', 'pollution']"}
现在我想在每一行中找到“技术”一词并对键求和。像这里一样,我应该有 4722 + 3200 + 1697 的总和。
谁能帮帮我?
我应该提到我的原始数据框有 2000 行。
请您参考如下方法:
使用 sum() 内置函数,传递适当的生成器表达式:sum(k for k,v in d.items() if 'technology' in v)(注意在 Python2 中使用 d.iteritems())。
可运行的演示:
d = {
4722: "['children', 'dance', 'education','technology', 'teaching']",
3200: "['alternative energy', 'sustainability', 'technology']",
1636: "['computers', 'performance', 'simplicity', 'software', 'ice']",
1697: "['MacArthur grant', 'inequality', 'technology', 'pollution']"
}
result = sum(k for k,v in d.items() if 'technology' in v)
assert result == 9619
引用资料:
