如何检查列表中是否只有两个可以重复的特定元素?

npa*_*tel 4 python python-2.7

如何检查列表中是否只有两个可以重复的特定元素?

例如:我希望出现在列表中的有效元素只有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)

iz_*_*iz_ 6

您可以使用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)

  • 从数学上来说,@ StephenMason从数学上来说,一个空列表会满足它,条件是[非常正确](https://en.wikipedia.org/wiki/Vacuous_truth)。 (3认同)