【问题标题】:Python Dictionary Filtration with items as a list将项目作为列表的 Python 字典过滤
【发布时间】:2020-12-30 20:55:42
【问题描述】:

我的字典中有几个列表作为项目。我想创建一个具有相同键的字典,但仅包含与第一个键中列表的唯一值相对应的项目。最好的方法是什么? 原文:

d = {'s': ['a','a','a','b','b','b','b'],
     'd': ['c1','d2','c3','d4','c5','d6','c7'],
     'g': ['e1','f2','e3','f4','e5','f6','e7']}

输出:

e = {'s': ['a','a','a'],
     'd': ['c1','d2','c3'],
     'g': ['e1','f2','e3']}

f = {'s': ['b','b','b','b'],
     'd': ['d4','c5','d6','c7'],
     'g': ['f4','e5','f6','e7']}

【问题讨论】:

  • 你能分享你试过的代码吗?以及您在使用该代码时遇到了什么问题?

标签: python list loops dictionary


【解决方案1】:

我认为没有简单的方法可以做到这一点。我为你创建了一个(不是那么)小函数:

def func(entry):
    PARSING_KEY = "s"
    # check if entry dict is valid (optional)
    assert type(entry)==dict

    for key in entry.keys():
        assert type(entry[key])==list

    first_list = entry[PARSING_KEY]
    first_list_len = len(first_list)
    for key in entry.keys():
        assert len(entry[key]) == first_list_len

    # parsing
    output_list_index = []
    already_check = set()
    for index1, item1 in enumerate(entry[PARSING_KEY]):
        if not item1 in already_check:
            output_list_index.append([])
            for index2, item2 in enumerate(entry[PARSING_KEY][index1:]):
                if item2==item1:
                    output_list_index[-1].append(index2)
            already_check.add(item1)

    # creating lists
    output_list = []
    for indexes in output_list_index:
        new_dict = {}
        for key, value in entry.items():
            new_dict[key] = [value[i] for i in indexes]
        output_list.append(new_dict)

    return output_list

请注意,由于 dict 的结构,没有“第一个键”,因此您必须硬编码要用于解析的键(函数顶部的“PARSING_KEY”常量)

【讨论】:

    【解决方案2】:
    original_dict = {
        'a': [1, 3, 5, 8, 4, 2, 1, 2, 7],
        'b': [4, 4, 4, 4, 4, 3],
        'c': [822, 1, 'hello', 'world']
    }
    distinct_dict = {k: list(set(v)) for k, v in original_dict.items()}
    distinct_dict
    

    产量

    {'a': [1, 2, 3, 4, 5, 7, 8], 'b': [3, 4], 'c': [1, 'hello', 'world', 822]}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 2020-02-09
      • 2017-10-29
      • 2021-07-11
      • 1970-01-01
      • 2022-01-23
      相关资源
      最近更新 更多