如何检查我的列表是否只有 2 个可以重复的特定元素?
例如:
我希望在我的列表中的有效元素只有 2 个:
1. abstract.f
2. None
如果 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.
最佳答案
您可以使用 all
输出 bool 值:
# 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
关于python - 如何检查我的列表是否只有 2 个可以重复的特定元素?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57192739/