Python:字典列表之间的减法

2024-05-16 04:01:16 发布

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

我有两个包含字典的列表,如下所示:

listone = [{'unit1': {'test1': 10}}, 
           {'unit1': {'test2': 45'}, 
           {'unit2': {'test1': 78'}, 
           {'unit2': {'test2': 2'}}]

listtwo = [{'unit1': {'test1': 56}}, 
           {'unit1': {'test2': 34'}, 
           {'unit2': {'test1': 23'}, 
           {'unit2': {'test2': 5'}}]

我还将所有单元名称和测试名称分别列在单独的列表中:

^{pr2}$

如何找到每个测试值的增量,即(test2-test1)的值,以便我最终可以按如下方式排列数据:

unit1, test1, delta
unit1, test2, delta
unit2, test1, delta
unit2, test2, delta

到目前为止,我有这些:

def delta(array1, array2):
        temp = []
        temp2 = []
        tmp = []
        tmp2 = []
        delta = []
        for unit in units:
            for mkey in array1:
                for skey in mkey:
                    if skey == unit:
                        temp.append(mkey[skey])
                        floater(temp) #floats all the values
                        for i in testnames:
                            for u in temp:
                                tmp.append(u[i])
                                tmp = filter(None, tmp2)

            for mkey in array2:
                for skey in mkey:
                    if skey == unit:
                        temp.append(mkey[skey])
                        floater(temp2)
                        for i in testnames:
                            for u in temp2:
                                tmp2.append(u[i])
                                tmp2 = filter(None, tmp2)

        delta = [tmp2 - tmp for tmp2, tmp in zip(tmp2, tmp)] 
        print delta

delta(listone,listtwo)

不幸的是,代码给出了Keyerror。:( 请帮帮我。谢谢。在


Tags: inforunittemptmpdeltatest1test2
3条回答

或许可以将数据转换为另一种更方便的数据结构。 例如,与listone不同,使用这样的单个dict会更容易:

{('unit1', 'test1'): 10,
 ('unit2', 'test1'): 78,
 ('unit2', 'test2'): 2,
 ('unit1', 'test2'): 45}

既然如此

^{pr2}$

这里我们将listone和{}转换为dict列表:

dicts=[{},{}]
for i,alist in enumerate([listone,listtwo]):
    for item in alist:
        for unit,testdict in item.iteritems():
            for testname,value in testdict.iteritems():
                dicts[i][unit,testname]=value

现在找到deltas很容易:

for unit,testname in itertools.product(units,testnames):
    delta=dicts[1][unit,testname]-dicts[0][unit,testname]
    print('{u}, {t}, {d}'.format(u=unit,t=testname,d=delta))

收益率

unit1, test1, 46
unit1, test2, -11
unit2, test1, -55
unit2, test2, 3

我认为用字典比较容易。在这里,我按步骤定义它们,因为我假设您收集的是某个测试过程的结果,但您也可以在一行中完成。在

listOne = {}
listOne['unit1'] = {}
listOne['unit2'] = {}
listOne['unit1']['test1']=10
listOne['unit1']['test2']=45
listOne['unit2']['test1'] = 78
listOne['unit2']['test2'] = 2

listTwo = {}
listTwo['unit1'] = {}
listTwo['unit2'] = {}
listTwo['unit1']['test1']=56
listTwo['unit1']['test2']=34
listTwo['unit2']['test1'] = 23
listTwo['unit2']['test2'] = 5

units = ['unit1', 'unit2']
testnames = ['test1','test2']

deltas = {}

# collect the deltas
for unit in units :
    deltas[unit] = {}
    for test in testnames :
        deltas[unit][test] = listTwo[unit][test] -listOne[unit][test]

# print put the results
for unit in units :
    for test in testnames :
        print unit, ', ', test, ', ', deltas[unit][test]

这就产生了

^{pr2}$

类似,但更具封装性:

from collections import defaultdict

listone = [
    {'unit1': {'test1': 10}},
    {'unit1': {'test2': 45}}, 
    {'unit2': {'test1': 78}}, 
    {'unit2': {'test2': 2}}
]

listtwo = [
    {'unit1': {'test1': 56}},
    {'unit1': {'test2': 34}}, 
    {'unit2': {'test1': 23}}, 
    {'unit2': {'test2': 5}}
]

def dictify(lst):
    res = defaultdict(lambda: defaultdict(int))
    for entry in lst:
        for unit,testentry in entry.iteritems():
            for test,val in testentry.iteritems():
                res[unit][test] = val
    return res
    # returns dict['unitX']['testY'] = val

def genDeltas(dictA, dictB):
    units = dictA.keys()
    units.sort()
    tests = dictA[units[0]].keys()
    tests.sort()
    for unit in units:
        _A = dictA[unit]
        _B = dictB[unit]
        for test in tests:
            yield unit,test,(_B[test]-_A[test])

for unit,test,delta in genDeltas(dictify(listone),dictify(listtwo)):
    print "{0}, {1}, {2}".format(unit,test,delta)

编辑:要查找字段平均值:

^{pr2}$

相关问题 更多 >