可以使用单一理解来检查一组中的任何项目是否在另一组中?

问题描述 投票:0回答:1

我的单元测试中有以下检查:

any(pass1_task in (task for task in all_downstream_task_for_dl_task) for pass1_task in
                            {'first_pass', 'first_cpp_pass'}),'the test failed unexpectedly')

当我期望它通过时,上面的单元测试失败了。

all_downstream_task_for_dl_task
是一个包含 2 项的列表:

 {'cbbo_snowflake_copy_XAMS', 'first_cpp_pass.euronext3-equities_nl_A_3'}

实际上列表要长得多,但为了简单起见,我们假设它包含上述两个。

我的列表理解没有达到我的预期吗?

我希望单元测试能够通过,因为

all_downstream_task_for_dl_task
中的第二项包含
first_cpp_pass

python list-comprehension
1个回答
0
投票

当行溢出 79 个字符时,我通常会避免理解,不仅是因为 PEP 8,还因为它们失去了简化代码的主要目标。如果重构代码,使其在传统的 for 循环中循环遍历集合,则更容易看出您在子字符串检查操作中交换了两个成员的顺序。正确的代码是:

is_in_task = []
for task in all_downstream_task_for_dl_task:
    for pass1_task in {'first_pass', 'first_cpp_pass'}:
        is_in_task.append(pass1_task in task)

assert any(is_in_task), 'the test failed unexpectedly'

并且有理解力:

assert any(pass1_task in task for pass1_task in {'first_pass', 'first_cpp_pass'} for task in all_downstream_task_for_dl_task), 'the test failed unexpectedly'
© www.soinside.com 2019 - 2024. All rights reserved.