python - python字典问题的更好方法
问题描述
这是样本数据。输入目录中的所有内容都是动态的。唯一的问题是数据字典将为 input_dict 中的每个键值修复 7 个不同的值。它可能只有 1 或 0 个值。
input_dict = { 'all_val' : ['a', 'b', 'c' ],
'2nd_group' : ['a', 'b'] ,
'3rd_grp' : ['a' , 'c']}
data = {
'a' : [1,0,1,0,0,0,1],
'b' : [0,0,1,1,0,1,0],
'c' : [0,1,1,0,0,0,1] }
required_output = {'2nd_group': 5, '3rd_grp': 4, 'all_val': 6}
逻辑:对于 all_val,取 a、b 和 c 并转到数据字典。如果 a[0],b[0],c[0] 中的任何一个为 1,则应考虑 1。 a[1],b[1],c[1] 的方式相同 ...最后计算所有 1 .
我的解决方案:
temp_dict = {}
output_dict = {}
for a in input_dict.keys():
temp_dict[a] = [0]*7
for key, value in input_dict.items():
for v in value:
for j , d in enumerate(data[v]):
temp_dict[key][j] = max( temp_dict[key][j] , d )
for k,v in temp_dict.items():
total = 0
for t in temp_dict[k]:
total = total + t
output_dict[k] = total
print output_dict
有没有办法提高性能或解决这个问题的任何其他方法。
解决方案
我的方法使用七个元素并行计算列表中的所有项目,并且不需要像 numpy 那样单独安装的项目。在 Python 3 中,它读取:
import operator
import functools
input_dict = { 'all_val' : ['a', 'b', 'c' ],
'2nd_group' : ['a', 'b'] ,
'3rd_grp' : ['a' , 'c']}
data = {
'a' : 0b1010001,
'b' : 0b0011010,
'c' : 0b0110001}
def num_bits(n):
result = 0
while n > 0:
result += n & 1
n >>= 1
return result
if __name__ == '__main__':
result = {}
for inkey, labels in input_dict.items():
result[inkey] = num_bits(functools.reduce(operator.__or__, (data[l] for l in labels)))
print(result)
完全冒险的人甚至可以用字典理解来代替主要部分:
print({inkey: num_bits(functools.reduce(operator.__or__, (data[l] for l in labels))) for inkey, labels in input_dict.items()})
推荐阅读
- java - 如何在java中进行URL通配符匹配?
- docker - 如何在 github 操作服务容器中运行命令?
- python - 解析“conda”、“sudo”和“全局”python 路径
- java - 中断一个java套接字
- flutter - 如何拥有需要用户 ID 的流提供程序?
- java - 使用 url android studio (Java) 设置壁纸
- f# - F# CsvProvider MissingMethodException
- javascript - 在一个 WordPress 主题上调整浏览器窗口的大小以及添加 JS 代码移动菜单关闭按钮后,导航栏不起作用
- scala - 惰性 val 如何解决前向引用扩展 scala 中的值定义
- python - 带有额外空格的 CSV