【问题标题】:Removing elements from a dictionary consisting of tuples calculating the last element in the tuple and the value in the dictionary从由元组组成的字典中删除元素,计算元组中的最后一个元素和字典中的值
【发布时间】:2021-02-24 22:51:47
【问题描述】:

给出以下字典:

a = {('a','b', 'c'):3,('a','d','c'):4, ('f','e','b'):5, ('r','t','b'):5.1}

字典由作为键的元组和作为值的数字组成。每个元组由一系列字母组成。 从最后一个元素相同的所有元组中,应排除字典值最低的元组。 例如元组('a','b', 'c') 和元组('a','d','c') 都将字母C 作为最后一个元素,因此应该删除值最低的那个。 参考上面的字典,结果应该是:

{('a','d','c'):4, ('r','t','b'):5.1}

【问题讨论】:

    标签: python dictionary tuples


    【解决方案1】:

    你可以这样做:

    from collections import defaultdict
    from operator import itemgetter
    
    a = {('a','b', 'c'):3,('a','d','c'):4, ('f','e','b'):5, ('r','t','b'):5.1}
    
    # group the items by the last element of the key of the tuple
    lookup = defaultdict(list)
    for key, value in a.items():
        lookup[key[2]].append((key, value))
    
    # find the maximum in each group by the value of the tuple
    result = dict(max(value, key=itemgetter(1)) for value in lookup.values())
    
    print(result)
    

    输出

    {('a', 'd', 'c'): 4, ('r', 't', 'b'): 5.1}
    

    【讨论】:

      【解决方案2】:

      代码:

      a = {('a','b', 'c'):3,('a','d','c'):4, ('f','e','b'):5, ('r','t','b'):5.1}
      
      keys_to_remove = []
      for key in a.keys():
          srch_key = key[-1]
          lowest_val = min(v for k,v in a.items() if k[-1] == srch_key)
          keys_to_remove.append(*(k for k,v in a.items() if k[-1] == srch_key and v == lowest_val))
          
      for key_to_remove in set(keys_to_remove):
          a.pop(key_to_remove)
      print(a)
              
      

      输出:

      {('a', 'd', 'c'): 4, ('r', 't', 'b'): 5.1}
      

      【讨论】:

        【解决方案3】:

        另一种解决方案可能是:

        a_dict = {('a','b', 'c'):3,('a','d','c'):4, ('f','e','b'):5, ('r','t','b'):5.1}
        
        
        b_dict = dict()
        seq = 2
        for key in a_dict:
            b_key = find_key(b_dict, key[seq])
            if b_key is not None:
                b_dict.pop(b_key)
                b_dict[key] = a_dict[key]
            else:
                b_dict[key] = a_dict[key]
        
        
        def find_key(x_dict, k, seq=2):
            for key in x_dict:
                if key[seq] == k:
                    return key
            return None
        

        创建一个空字典。遍历字典,在新字典中搜索键元组的最后一个元素。如果不存在,则将 key:value 添加到新的 dict 中。 如果找到,请检查其值是否更大。如果不是,请删除该元素并添加新的 key:value。

        【讨论】:

          猜你喜欢
          • 2015-12-30
          • 1970-01-01
          • 1970-01-01
          • 2014-07-23
          • 1970-01-01
          • 2021-04-09
          • 1970-01-01
          • 2011-08-16
          • 2015-03-16
          相关资源
          最近更新 更多