我有一个dict,如下所示:列表中的单元名和测试名:
dictA = {('unit1', 'test1'): 10, ('unit2', 'test1'): 78, ('unit2', 'test2'): 2, ('unit1', 'test2'): 45}
units = ['unit1', 'unit2']
testnames = ['test1','test2']
我们如何将test1的所有值附加到列表中? 即
temp = [10,78] # test1 values
temp2 = [2,45] # test2 values
答案 0 :(得分:2)
看起来你问的是list comprehensions。
[v for k,v in dictA.iteritems() if k[1] == 'test1']
会给你:
[10, 78]
类似地:
>>> [v for k,v in dictA.iteritems() if k[1] == 'test2']
[2, 45]
现在,key
是一个元组,我们引用了if
- 子句中的元素。
答案 1 :(得分:1)
temp = [ j for i, j in dictA.iteritems() if "test1" in i ]
答案 2 :(得分:1)
我会把dictA变成一个字典词典 - 无论是通过转换还是通过以这种形式构建它更好
dictA = {'unit1':{'test1': 10, 'test2': 2}, 'unit2': {'test1': 78, 'test2': 45}}
然后
temp = [dictA[x]['test1'] for x in units]
temp2 = [dictA[x]['test2'] for x in units]