【问题标题】:Merge two defaultdict with special char for non matching keys将两个带有特殊字符的 defaultdict 合并为不匹配的键
【发布时间】:2019-01-30 17:28:28
【问题描述】:

我有两个 defaultdict,如下所述:

L1 = [(10955, 'AB'), (10954, 'AB'), (10953, 'ABC'), (10952, 'ABCD'),(10951, 'ABCDEF')]
L2 = [(10956, 'A'), (10955, 'A'), (10954, 'ABE'), (10953, 'ABC'), (10952, 'ABCD')]

我想合并 defaultdict 并用 '#' 填充不匹配的键

RES = [(10956, '#', 'A'),(10955, 'AB', 'A'), (10954, 'AB', 'ABE'), (10953, 'ABC', 'ABC'), (10952, 'ABCD', 'ABCD'),(10951, 'ABCDEF', '#')]

【问题讨论】:

  • 您自己尝试过吗?你的代码在哪里?
  • 元组列表或默认字典?

标签: python python-3.x pandas collections tuples


【解决方案1】:

只需遍历排序的键,如果键不存在于任何一个字典中,则将默认值设置为'#'

from collections import OrderedDict
L1 = [(10955, 'AB'), (10954, 'AB'), (10953, 'ABC'), (10952, 'ABCD'),(10951, 'ABCDEF')]
L2 = [(10956, 'A'), (10955, 'A'), (10954, 'ABE'), (10953, 'ABC'), (10952, 'ABCD')]

L1=OrderedDict(L1)
L2=OrderedDict(L2)

sorted_keys=sorted(set(L1.keys()+L2.keys()),reverse=True) #sorting the keys in reverse

d=OrderedDict() # new orderedDict to keep the results
for i in sorted_keys:
    d[i]=(L1.get(i,'#'),L2.get(i,'#'))

这会给

OrderedDict([(10956, ('#', 'A')),
             (10955, ('AB', 'A')),
             (10954, ('AB', 'ABE')),
             (10953, ('ABC', 'ABC')),
             (10952, ('ABCD', 'ABCD')),
             (10951, ('ABCDEF', '#'))])

要得到最终输出为list 然后将上面的代码修改为

lis=[]
for i in sorted_keys:
    lis.append((i,L1.get(i,'#'),L2.get(i,'#')))

输出

[(10956, '#', 'A'),
 (10955, 'AB', 'A'),
 (10954, 'AB', 'ABE'),
 (10953, 'ABC', 'ABC'),
 (10952, 'ABCD', 'ABCD'),
 (10951, 'ABCDEF', '#')]

【讨论】:

    【解决方案2】:

    你可以使用熊猫:

    import pandas as pd
    d1 = pd.DataFrame().from_dict(dict(L1), orient='index')
    
    d2 = pd.DataFrame().from_dict(dict(L2), orient='index')
    
    pd.concat([d1,d2], axis=1).fillna('#').reset_index().apply(tuple, axis=1).tolist()
    

    输出:

    [(10951, 'ABCDEF', '#'), (10952, 'ABCD', 'ABCD'), (10953, 'ABC', 'ABC'), (10954, 'AB', 'ABE'), (10955, 'AB', 'A'), (10956, '#', 'A')]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-20
      • 1970-01-01
      • 2021-01-10
      • 2013-07-20
      • 2020-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多