我知道
all(map(compare,new_subjects.values()))==True
告诉我如何判断列表中的每个元素是否都为True。但是,如果除了其中一个元素外,其他所有元素都是True,我该如何判断?
我知道
all(map(compare,new_subjects.values()))==True
告诉我如何判断列表中的每个元素是否都为True。但是,如果除了其中一个元素外,其他所有元素都是True,我该如何判断?
values = map(compare, new_subjects.values())
len([x for x in values if x]) == len(values) - 1
基本上,您需要过滤列表中的True值,并比较该列表的长度与原始列表的长度是否相差1。filter(None, values)
做的是同样的事情 ;p - Jochen RitzelTrue
而不是评估为True,那么你只需计算它们即可。>>> L1 = [True]*5
>>> L1
[True, True, True, True, True]
>>> L2 = [True]*5 + [False]*2
>>> L2
[True, True, True, True, True, False, False]
>>> L1.count(False)
0
>>> L2.count(False)
2
>>>
检查是否只有一个False:
>>> def there_can_be_only_one(L):
... return L.count(False) == 1
...
>>> there_can_be_only_one(L1)
False
>>> there_can_be_only_one(L2)
False
>>> L3 = [ True, True, False ]
>>> there_can_be_only_one(L3)
True
>>>
编辑:实际上这更好地回答了你的问题:
>>> def there_must_be_only_one(L):
... return L.count(True) == len(L)-1
...
>>> there_must_be_only_one(L3)
True
>>> there_must_be_only_one(L2)
False
>>> there_must_be_only_one(L1)
False
计算有多少个不是True的值:
values = (compare(val) for val in new_subjects.itervalues())
if sum(1 for x in values if not x) == 1: # just one
...
values = new_subjects.values()
sum(compare(v) for v in values) == len(values) -1