将两个多维列表合并为一个列表

时间:2017-05-31 11:40:10

标签: python python-3.x

我有两个要合并的列表:

list1 = [['desktop', '10022'], ['mobile', '119'], ['tablet', '7']]
list2 = [['desktop', '9964'], ['mobile', '117'], ['tablet', '8']]

我想将它们安排到这个列表中:

new_list = [('desktop', ['10022', '9964']), ('mobile', ['119', '117']), ('tablet', ['7', '8'])]

然后,我还想计算整数之间的百分比差异,并在列表中插入答案:

updated_list = [['desktop', '10022', '9964', '0.5821'], ['mobile', '119', '117', '1.7094'], ['tablet', '7', '8', '-12.5']]

这是我粗略的代码:

from collections import OrderedDict

list1 = [['desktop', '10022'], ['mobile', '119'], ['tablet', '7']]
list2 = [['desktop', '9964'], ['mobile', '117'], ['tablet', '8']]

merged = OrderedDict()

for list_ in list1, list2:
    for k, v in list_:
        try:
            merged[k].append(v)
        except:
            merged[k] = [v]

def diff(x, y):
    return ((x/y)-1)*100

updated_list = [[row,x,y,diff(x,y) for x,y in vals.items()] for row,vals in merged.items()]

无法让这件事发挥作用:(

3 个答案:

答案 0 :(得分:5)

假设您的列表已排序且同质,您可以

[[k, int(v1), int(v2), int(v1)/int(v2) - 1] for ((k, v1), (_, v2)) in zip(list1, list2)]

如果列表数据是同质的,但没有排序,只需调用

即可
list1.sort()
list2.sort()

在处理之前。如果数据不是同类的,那么迭代的简单方法是将列表转换为字典并迭代通用键:

d1, d2 = dict(list1), dict(list2)
[[k, int(d1[k]), int(d2[k]), int(d1[k])/int(d2[k]) -1] for k in d1.keys() & d2.keys()]

答案 1 :(得分:3)

这是一个有效的代码:

# The same, and then

updated_list = [(row, vals[0], vals[1], diff(int(vals[0]), int(vals[1]))) for row, vals in merged.items()]
print(updated_list)

您的问题是您要从x解包yvals,但除非valstuples的列表,否则您无法解决此问题}。

答案 2 :(得分:1)

updated_list = [[row,x,y,diff(x,y) for x,y in vals.items()] for row,vals in merged.items()]

vals是一个列表,因此它没有方法items(),内部列表理解有语法错误,即使它是[(row,x,y,diff(x,y) )for x,y in vals.items()]或其他类似的也无法工作,因为错误的方法调用。另外,您不会使用for x,y in vals解压缩2的列表。例如,你可以解压缩这样的2元组列表。

这会偏离您尝试过的,但您可以创建一个有序的默认字典,合并并进行计算:

In [1]: from collections import OrderedDict

In [2]: class OrderedDefaultDict(OrderedDict):
   ...:     def __missing__(self, key):
   ...:         obj = self[key] = self.default_factory()
   ...:         return obj
   ...:     def __init__(self, default_factory, *args, **kwgs):
   ...:         super().__init__(*args, **kwgs)
   ...:         self.default_factory = default_factory
   ...:         

In [11]: list1 = [['desktop', '10022'], ['mobile', '119'], ['tablet', '7']]

In [12]: list2 = [['desktop', '9964'], ['mobile', '117'], ['tablet', '8']]

In [14]: merged = OrderedDefaultDict(list)

In [16]: from itertools import chain

In [17]: for k, v in chain(list1, list2):
    ...:     merged[k].append(v)
    ...:     

In [18]: merged
Out[18]: OrderedDefaultDict([('desktop', ['10022', '9964']), ('mobile', ['119', '117']), ('tablet', ['7', '8'])])

In [19]: def diff(x, y):
   ....:     return ((x/y)-1)*100                                                                                          
   ....: 

In [20]: [[k, x, y, str(diff(float(x), float(y)))]
    ...:  for k, (x, y) in merged.items()]
Out[20]:                                                                                                                                    
[['desktop', '10022', '9964', '0.5820955439582498'],                                                                                        
 ['mobile', '119', '117', '1.7094017094017033'],                                                                                                   
 ['tablet', '7', '8', '-12.5']]                                                                                                                    

或者根据需要格式化浮点数,例如

'{:.4f}'.format(diff(...))