【问题标题】:return the key whose values are repeated返回其值重复的键
【发布时间】:2018-11-12 00:36:20
【问题描述】:

我有一个字典,其键值是列表。每个列表可能包含一些重复多次的值,就像这样

{'VSS': ['A2', 'A3', 'A1'], 'X_P1_1': ['A2', 'A1'], 'X_P2': ['A3', 'A2'], 'X_P1_3': ['A2', 'A1'], 'VDD': ['A3', 'A3', 'A3', 'A3', 'A3', 'A3', 'A3', 'B', 'A3'], 'X': ['B', 'A1', 'A1', 'A1', 'A1', 'A1', 'A1', 'A1', 'B', 'A1']}

我想做一个循环来获取频率大于 1 的键 例如:

VDD: ['A3':8]
X : ['A1':8, 'B':2]

如何做到这一点?

【问题讨论】:

  • 你会接受熊猫吗?
  • @W-B 什么是熊猫?

标签: python dictionary for-loop counter


【解决方案1】:

你可以使用Counter:

from collections import Counter

data = {'VSS': ['A2', 'A3', 'A1'], 'X_P1_1': ['A2', 'A1'], 'X_P2': ['A3', 'A2'], 'X_P1_3': ['A2', 'A1'], 'VDD': ['A3', 'A3', 'A3', 'A3', 'A3', 'A3', 'A3', 'B', 'A3'], 'X': ['B', 'A1', 'A1', 'A1', 'A1', 'A1', 'A1', 'A1', 'B', 'A1']}


result = {key : { e: count for e, count in Counter(values).items() if count > 1}  for key, values in data.items() if any(value > 1 for value in Counter(values).values())}

print(result)

输出

{'VDD': {'A3': 8}, 'X': {'B': 2, 'A1': 8}}

或者,如果您更喜欢将值作为元组列表:

from collections import Counter

data = {'VSS': ['A2', 'A3', 'A1'], 'X_P1_1': ['A2', 'A1'], 'X_P2': ['A3', 'A2'], 'X_P1_3': ['A2', 'A1'],
        'VDD': ['A3', 'A3', 'A3', 'A3', 'A3', 'A3', 'A3', 'B', 'A3'],
        'X': ['B', 'A1', 'A1', 'A1', 'A1', 'A1', 'A1', 'A1', 'B', 'A1']}

result = {key: [(element, count) for element, count in counts.items() if count > 1] for key, counts in map(lambda x: (x[0], Counter(x[1])), data.items()) if
          any(count > 1 for count in counts.values())}
print(result)

输出

{'VDD': [('A3', 8)], 'X': [('A1', 8), ('B', 2)]}

【讨论】:

    【解决方案2】:

    使用collections.Counter:

    from collections import Counter
    
    # count values in lists, only including counts greater than 1
    c = {k: {val: count for val, count in Counter(v).items() if count > 1} \
         for k, v in d.items()}
    
    # isolate only keys where Counter value is non-empty
    res = {k: v for k, v in c.items() if v}
    
    {'VDD': {'A3': 8},
     'X': {'B': 2, 'A1': 8}}
    

    【讨论】:

    • 括号内的表达式不需要续行 ;-)
    • @coldspeed,是的,我知道 :)。但我发现它更具可读性.. 我可以看到自己在一行的末尾看到 } 并认为理解到此为止!
    【解决方案3】:

    第一步是反转映射。

    valuekeydict = {}
    for k, vs in orig_dict.items():
        for v in vs:
            valuekeydict.setdefault(v, []).append(v)
    

    然后获取一组len > 1的所有值

    result = {v for vs in valuekeydict.values() for v in vs if len(vs) > 1}
    

    【讨论】:

      猜你喜欢
      • 2020-05-24
      • 2021-08-10
      • 2013-07-14
      • 1970-01-01
      • 2023-03-19
      • 2013-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多