【发布时间】: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