" all" Python中的函数工作?

时间:2016-02-28 17:26:30

标签: python python-3.x

我在Python中搜索了对all函数的理解,并根据此处找到了this

  只有当所有元素都是Truthy时,

all才会返回True

但是当我使用这个功能时,它的表现不同:

'?' == True   # False
'!' == True   # False
all(['?','!']) # True

为什么当输入中的所有元素都是False时,它会返回True?我误解了它的功能还是有解释?

3 个答案:

答案 0 :(得分:9)

  

仅当所有元素都是 Truthy

Truthy!= True

all基本上会检查bool(something)True(对于迭代中的所有something)。

>>> "?" == True
False
>>> "?" == False # it's not False either
False
>>> bool("?")
True

答案 1 :(得分:1)

'?'和'!'都是真的,因为它们是非空的字符串。

<?xml version="1.0" encoding="UTF-8"?> <persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"> <persistence-unit name="spring-data-jpa-krishna" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <class>net.javabeat.springdata.model.Address</class> <class>net.javabeat.springdata.model.Employee</class> <!-- http://docs.oracle.com/cd/E16439_01/doc.1013/e13981/cfgdepds005.htm --> <properties> <property name="javax.persistence.jdbc.url" value="${jdbc.mysql.url}" /> <property name="javax.persistence.jdbc.driver" value="${jdbc.mysql.driver.class}" /> <property name="javax.persistence.jdbc.user" value="${jdbc.mysql.username}" /> <property name="javax.persistence.jdbc.password" value="${jdbc.mysql.password}" /> <property name="eclipselink.logging.level" value="FINE" /> <property name="eclipselink.ddl-generation" value="create-tables" /> </properties> </persistence-unit> </persistence> 和“truthy”之间存在差异。 Truthy意味着当被胁迫时,它可以评估为True。这与True==不同。

答案 2 :(得分:-1)

当我们想要检查列表中的所有项是否可迭代时,使用

all()函数。 例如: x=[1,2,3,4,5] all(x) 它将返回True。