列表的每个元素都是True布尔值

Gla*_*wed 20 python

我知道

all(map(compare,new_subjects.values()))==True
Run Code Online (Sandbox Code Playgroud)

会告诉我列表中的每个元素是否为True.但是,如何判断除其中一个元素之外的每个元素是否为True?

Raf*_*ler 11

values = map(compare, new_subjects.values())
len([x for x in values if x]) == len(values) - 1
Run Code Online (Sandbox Code Playgroud)

基本上,您过滤列表中的真值,并将该列表的长度与原始列表进行比较,以查看它是否少一个.

  • @Giacomo:列表推导是一个强大的功能,如果你学习任何Python,你很快就会了解它们.我将*不*将我的代码中使用的功能限制为C中存在的功能,以便C程序员可以理解它.当您尝试读取语言L中的代码时,您*必须*知道一些L. (5认同)
  • 但列表理解很简单.每个了解它们并使用它们几天的人都很了解它们.正如我之前所说,它们不是一个模糊的功能,它们在完全可读的Python代码中非常常见.不,你的代码(PHP或其他)对任何人都不可理解.如果他们习惯于使用完全不同的语言,那么即使对所有程序员来说也是如此.它没有必要.除此之外,您是否会为此目的避免使用例如字符串插值? (2认同)

DTi*_*ing 7

如果你的意思是实际True而不是评估为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
>>> 
Run Code Online (Sandbox Code Playgroud)

只检查一个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
>>> 
Run Code Online (Sandbox Code Playgroud)

编辑:这实际上更好地回答了你的问题:

>>> 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
Run Code Online (Sandbox Code Playgroud)