You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python 3.8+中以字典为参考过滤嵌套列表(问卷场景)

解决方案:基于控制问题字典过滤问卷响应列表

核心思路

要过滤嵌套格式的问卷响应列表,需遍历每个响应,检查控制问题字典中指定的所有题目(转换为列表索引)的答案是否完全匹配预期值。注意题目编号是1-based(如第3题、第7题),而列表索引是0-based,因此需要将题目编号减1得到对应索引位置。

实现代码

以下提供两种符合需求的实现方式,优先推荐简洁高效的列表推导式,同时给出循环版便于理解:

方式1:列表推导式(推荐)

利用列表推导式结合all()函数,一次性完成过滤逻辑:

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 = [
    resp for resp in unfiltered_responses
    if all(resp[q_num - 1] == expected_val for q_num, expected_val in control_questions.items())
]

for response in filtered_responses:
    print(response)

方式2:显式循环(适合新手理解)

通过逐一遍历响应和控制问题,明确判断每个响应的有效性:

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 = []
for response in unfiltered_responses:
    valid = True
    # 遍历所有控制问题,逐一检查答案
    for q_num, expected in control_questions.items():
        # 转换为列表索引:题目编号减1
        if response[q_num - 1] != expected:
            valid = False
            break  # 只要有一个不满足,直接终止检查
    if valid:
        filtered_responses.append(response)

for response in filtered_responses:
    print(response)

关键说明

  • 索引转换:控制问题字典的键是1-based的题目编号,需减1得到列表的0-based索引(如第3题对应索引2,第7题对应索引6)。
  • 全条件满足:通过all()或循环判断,确保所有控制问题的答案都符合预期,只要有一个不满足就排除该响应。
  • 保留重复值:两种方式都会完整保留所有满足条件的响应,即使存在完全相同的数组内容,符合需求。

运行结果

执行代码后,filtered_responses会输出两个符合要求的响应:

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

内容的提问来源于stack exchange,提问作者paaskanama

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 00:40:40