【问题标题】:Filter a Python list using Dictionary keys and values使用字典键和值过滤 Python 列表
【发布时间】:2023-01-14 04:34:58
【问题描述】:

目标:在 Python 3.8+ 中使用字典作为参考过滤列表列表

案例使用:在查看嵌套列表(一系列调查回复)时,根据控制问题过滤掉回复。在词典中,对问题的回答 3(列表中的索引 2)和 7(索引 6)两者都应具有相应的值 5。如果响应的两个答案都不是 5,则它们应该不是填充在 filtered_responses 列表中。

开放解释如何解决这个问题。我已经查看了一些涉及使用列表过滤字典的资源。此方法是首选,因为一些调查响应中许多包含相同的值数组,因此保留了列表元素。

no_of_survey_questions = 10
no_of_participants = 5
min_score = 1
max_score = 10

control_questions = {3: 5,
                     7: 5, }

unfiltered_responses = [[4, 5, 4, 5, 4, 5, 4, 5, 4, 5],  # omit
                        [9, 8, 7, 6, 5, 4, 3, 2, 1, 1],  # omit
                        [5, 5, 5, 5, 5, 5, 5, 5, 5, 5],  # include
                        [5, 2, 5, 2, 5, 2, 5, 9, 1, 1],  # include
                        [1, 2, 5, 1, 2, 1, 2, 1, 2, 1]]  # omit

for response in unfiltered_responses:
    print(response)

print()

filtered_responses = []  # should contain only unfiltered_responses values marked 'include'
for response in filtered_responses:
    # INSERT CODE HERE
    print(response)

提前致谢!

【问题讨论】:

  • 你试过什么了?
  • @JonSG 列出的尝试太多,但每个网络搜索查询都返回了“过滤字典”的响应。首先,我试图将每个字典键等同于相应的索引,但无法找到一个有效的解决方案来遍历给定元素的字典。

标签: python dictionary filter nested-lists


【解决方案1】:

您可以使用列表理解 + all()

control_questions = {3: 5,
                     7: 5}

unfiltered_responses = [[4, 5, 4, 5, 4, 5, 4, 5, 4, 5],  # omit
                        [9, 8, 7, 6, 5, 4, 3, 2, 1, 1],  # omit
                        [5, 5, 5, 5, 5, 5, 5, 5, 5, 5],  # include
                        [5, 2, 5, 2, 5, 2, 5, 9, 1, 1],  # include
                        [1, 2, 5, 1, 2, 1, 2, 1, 2, 1]]  # omit

filted_questions = [subl  for subl in unfiltered_responses if all(subl[k-1] == v for k, v in control_questions.items())]
print(filted_questions)

印刷:

[
   [5, 5, 5, 5, 5, 5, 5, 5, 5, 5], 
   [5, 2, 5, 2, 5, 2, 5, 9, 1, 1]
]

【讨论】:

  • 将 subl[k] 稍微修改为 subl[k-1] 以将文字字典键与列表索引对齐,看起来这样可行。谢谢!
  • @paaskanama 是的,subl[k-1],我粘贴了错误的代码 :) 已修复。
猜你喜欢
  • 2015-05-17
  • 2020-10-30
  • 1970-01-01
  • 1970-01-01
  • 2018-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-21
相关资源
最近更新 更多