繁体   English   中英

检查元素是否在列表的任何地方

[英]check if element is in anywhere the list

我有两个列表:

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

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

我尝试过的事情:

for i in expected:
   assert i in actual

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

编辑:列表可以有不同的长度。

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

for act in actual:
    if not act.startswith(tuple(expected)):
        print(act)
>>>
orange

如果你想让它以相反的方式工作,

expected = ["apple", "banana", "pear", 'grapes']
actual = ["banana_yellow", "apple", "pear_green", 'orange']
expected_ = set(expected)
for act in actual:
    for exp in expected:
        if act.startswith(exp):
            expected_.discard(exp)
            break
assert not(expected_), f"{expected_} are not found in actual and " + f"{set(expected)-expected_} are found in actual"
>>>
AssertionError: {'grapes'} are not found in actual and {'apple', 'pear', 'banana'} are found in actual

其它的办法,

expected = ["apple", "banana", "pear", 'grapes']
actual = ["banana_yellow", "apple", "pear_green", 'orange']
for exp in expected:
    assert [exp for act in actual if act.startswith(exp)], f'{exp} not found'
>>>
AssertionError: grapes not found

试试这个:

def isequal(actual: list, expected: list) -> bool:
    actual.sort()
    expected.sort()
    if len(actual) != len(expected):
        return False
    for i, val in enumerate(expected):
        if not actual[i].startswith(val):
            return False
    return True

print(isequal(actual, expected))

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

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

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

它仍然有一个缺陷,如果你将orange添加到carot并且正在寻找orange ,它也会成功断言。 对于这种情况,您需要根据您的实际需要调整方法。 (例如,将substring in string替换为string.startwith(substring)等。但是,这应该给您一个起点:

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 any(expected_value in entry for entry in actual):
            raise AssertionError(f'Expected entry "{expected_value}" not found')

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

您可以使用.startswith以及排序列表来查找它。

expected = ["apple", "banana", "pear"]
actual = ["banana_yellow", "apple", "pear_green"]
expected.sort() # just looking for prefixes
actual.sort()
count = 0
for i in actual:
    if i.startswith(expected[count]): # prefix matches!
        count+=1 # move to next prefix
if count != len(expected): # since it didn't find all expected
    print("Nope!")
    assert False

它之所以有效,是因为它只是跳过actual actual找不到前缀, count就会卡住,导致count永远不会到达expected的末尾。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM