【问题标题】:resulting lists to a tuple (as described in the description, using the tuple function) and the resulting tuples need to be in a list结果列表到元组(如描述中所述,使用 tuple 函数)并且结果元组需要在列表中
【发布时间】:2021-02-08 17:09:08
【问题描述】:

以下是我从字典列表和元组中的排序数据中提取的代码

def compress(data):
    res = []
    for idx, sub in enumerate(data, start=0):
        if idx == 0:
            res.append(tuple(sub.keys()))
            res.append(list(sub.values()))
        else:
            res.append(list(sub.values()))
    return tuple(res)

data = [
    {"a": 1, "b": 2, "c": 3},
    {"a": 4, "c": 6, "b": 5}
]

print(compress(data))

预期结果是:

(('a', 'b', 'c'), [(1, 2, 3), (6, 5, 4)])

我的代码无法返回预期的结果。

【问题讨论】:

  • 你不是说:(('a', 'b', 'c'), [(1, 2, 3), (4, 5, 6)])
  • def compress(data): return (tuple(data[0].keys()), [tuple(x.values()) for x in data])
  • @Booboo 不行,结果必须是(6,5,4)
  • 6, 5, 4 分别是键 c, b 和 a 的值。你是说我们应该使用这些值吗?
  • def compress(data): return (('a', 'b', 'c'), [(1, 2, 3), (6, 5, 4)]) 似乎有效,但我无法解释原因。

标签: python list sorting dictionary tuples


【解决方案1】:

应该是

def compress(data):
    res = []
    for idx, sub in enumerate(data, start=0):
        if idx == 0:
            res.append(tuple(sub.keys()))
            res.append([])
            res[-1].append(tuple(sub.values()))
        else:
            res[-1].append(tuple(sub.values()))
    return tuple(res)

【讨论】:

  • 非常感谢。它现在可以工作了,因为我可以将我的结果转换为列表中的元组。但是我在排序函数中仍然面临一些困难,将值排序为(6,5,4),如果有任何建议,我真的很感激。
  • 这会产生:(('a', 'b', 'c'), [(1, 2, 3), (4, 6, 5)])这是公认的答案吗?
  • 要按降序对第二个列表进行排序,请使用sorted(...,reverse=True)
  • 我的代码现在是 def compress(data): res = [] for idx, sub in enumerate(data, start=0): if idx == 0: res.append(tuple(sub. keys())) res.append([]) res[-1].append(tuple(sub.values())) else: res[-1].append(tuple(sorted(sub.values(),reverse =True))) 返回元组(res)
【解决方案2】:

使用列表推导:

def compress(data):
  keys = tuple(sorted(data[0].keys()))
  values = [tuple(d[k] for k in keys) for d in data]
  return (keys, values)

>>> compress([{"a": 1, "b": 2, "c": 3},{"a": 4, "c": 6, "b": 5}])
(('a', 'b', 'c'), [(1, 2, 3), (4, 5, 6)])

可选:缺少键

如果某些字典中可能缺少某些键,您可以使用所有字典中的所有键,然后使用set 删除重复的键,然后使用d.get(k, default_value) 而不是d[k]

def compress(data, default_value=None):
  keys = tuple(sorted(set(k for d in data for k in d.keys())))
  values = [tuple(d.get(k, default_value) for k in keys) for d in data]
  return (keys, values)

>>> data = [{'a':1, 'b': 2, 'c': 3}, {'a':11, 'b':12, 'd':14}]
>>> compress(data, 0)
(('a', 'b', 'c', 'd'), [(1, 2, 3, 0), (11, 12, 0, 14)])

可选:存储此数据的另一种方式

您可以将此字典列表重构为列表字典:

def refactor(data):
  keys = data[0].keys()
  return { k: [d[k] for d in data] for k in keys }

>>> refactor([{"a": 1, "b": 2, "c": 3},{"a": 4, "c": 6, "b": 5}])
{'a': [1, 4], 'b': [2, 5], 'c': [3, 6]}

同样,您可以小心丢失键:

def refactor(data):
  keys = set(k for d in data for k in d.keys())
  return { k: [d[k] for d in data if k in d] for k in keys }

>>> refactor([{'a':1, 'b': 2, 'c': 3}, {'a':11, 'b':12, 'd':14}])
{'d': [14], 'a': [1, 11], 'c': [3], 'b': [2, 12]}

【讨论】:

    【解决方案3】:

    所以我创建了你想要的,你可以把它放在一个函数中,如果你愿意的话

    data = [
        {"a": 1, "b": 2, "c": 3},
        {"a": 4, "c": 6, "b": 5}
    ]
    
    keys = [[],[]]
    for d in data:
        items = list(d.items())
        l = []
        for i in items:
            l.append(i[1])
            if i[0] not in keys[0]:
                keys[0].append(i[0])
            else:
                continue
        keys[1].append(tuple(l))
    
    keys = tuple(keys)
    

    【讨论】:

      【解决方案4】:
      def compress(data):
          result = []    
          keys = tuple(data[0].keys()) # the keys
          result.append(keys)
          result2 = []
          result2.append(tuple([data[0][key] for key in keys]))
          result2.append(tuple([data[1][key] for key in keys[::-1]]))
          result.append(result2)
          return tuple(result)
      
      data = [
          {"a": 1, "b": 2, "c": 3},
          {"a": 4, "c": 6, "b": 5}
      ]
      
      print(compress(data))
      

      打印:

      (('a', 'b', 'c'), [(1, 2, 3), (6, 5, 4)])
      

      【讨论】:

      • 所以对于预期的结果,它应该在元组中列出一个值,但这个几乎就在那里
      猜你喜欢
      • 1970-01-01
      • 2019-04-27
      • 1970-01-01
      • 1970-01-01
      • 2021-11-02
      • 2014-01-02
      • 2014-03-06
      • 2013-12-24
      相关资源
      最近更新 更多