如何检查列表中是否只有两个可以重复的特定元素?
例如:我希望出现在列表中的有效元素只有2个:
1. abstract.f
2. None
Run Code Online (Sandbox Code Playgroud)
如果list包含任何其他元素,则应抛出错误消息。
list1 = ['abstract.f', None, None, 'abstract.f']
# This is a valid list as it doesn't have any other element than 2 of above.
list1 = ['abstract.f', None, 'xyz']
# This is invalid list as it has 'xyz' which is not expected.
Run Code Online (Sandbox Code Playgroud)
您可以使用all输出布尔值:
# Put items considered valid in this list
valid = ['abstract.f', None]
list1 = ['abstract.f', None, None, 'abstract.f']
print(all(el in valid for el in list1)) # True
list1 = ['abstract.f', None, 'xyz']
print(all(el in valid for el in list1)) # False
Run Code Online (Sandbox Code Playgroud)