【问题标题】:check if element is in anywhere the list检查元素是否在列表的任何地方
【发布时间】:2022-12-01 02:55:38
【问题描述】:

我有两个列表:

expected = ["apple", "banana", "pear"]
actual = ["banana_yellow", "apple", "pear_green"]

我试图断言预期 = 实际。即使在某些元素的末尾添加了颜色,它仍应返回 true。

我尝试过的事情:

for i in expected:
   assert i in actual

我希望这样的事情会起作用,但它试图将第一个元素 apple 与 banana 匹配并返回 false 而不是检查整个列表,如果列表中的任何地方都有 apple 则返回 true 。我希望有人能帮忙?

【问题讨论】:

  • [item.split('_')[0] for item in actual] 有帮助吗?
  • 这是假设它总是添加“_”,但事实可能并非如此。我更多地考虑了 .startswith() 之类的东西?或 .any() ?
  • 或者也许.contains()?
  • 你是什​​么意思“将第一个元素 apple 与 banana 匹配并返回 false 而不是检查整个列表并在列表中的任何位置有 apple 时返回 true”?它没有那样做。
  • 两个列表的长度是否相同?

标签: python list compare


【解决方案1】:

列表是可变的,您无法比较它们。尝试这个:

actual_wout_color = [item.split('_')[0] for item in actual]
actual_wout_color.sort()
expected.sort()
print(tuple(actual_wout_color) == tuple(expected))

【讨论】:

  • 什么?您绝对可以比较列表。
【解决方案2】:

我建议自定义断言方法..

这比您需要的要多一些,但也更灵活一些。

  • 条目的顺序无关紧要
  • 颜色的添加方式无关紧要(例如,通过破折号、下划线……)

它仍然有一个缺陷,如果你将颜色orange添加到carot并且正在寻找orange,它也会成功断言。对于这种情况,您需要根据实际需要调整方法。然而,这应该给你一个起点:

def assert_matching_list_contents(expected: list, actual: list) -> None:
    if len(expected) != len(actual):
        raise AssertionError('Length of the lists does not match!')

    for expected_value in expected:
        if not is_substring_of_entry(expected_value, actual):
            raise AssertionError(f'Expected entry "{expected_value}" not found')

def is_substring_of_entry(teststring: str, values: list) -> bool:
    for entry in values:
        if teststring in entry:
            return True
    return False


expectation = ["apple", "banana", "pear"]
current = ["banana_yellow", "apple", "pear_green"]
assert_matching_list_contents(expectation, current)

【讨论】:

  • 我喜欢那样,但如果可能的话,我希望能有更简单的东西……
猜你喜欢
  • 2021-10-30
  • 2011-11-03
  • 1970-01-01
  • 1970-01-01
  • 2010-11-23
  • 2019-10-04
  • 1970-01-01
  • 2012-04-03
相关资源
最近更新 更多