Python 遍历数据结构代码解释

Python iterating over a datastructure code explanation

我在 python 中使用 ldapsearch 编写代码并在 rosettacode.org

中遇到了这个 link
import ldap

l = ldap.initialize("ldap://ldap.example.com")
try:
    l.protocol_version = ldap.VERSION3
    l.set_option(ldap.OPT_REFERRALS, 0)

    bind = l.simple_bind_s("me@example.com", "password")

    base = "dc=example, dc=com"
    criteria = "(&(objectClass=user)(sAMAccountName=username))"
    attributes = ['displayName', 'company']
    result = l.search_s(base, ldap.SCOPE_SUBTREE, criteria, attributes)

    results = [entry for dn, entry in result if isinstance(entry, dict)]
    print results
finally:
    l.unbind()

这段代码我看不懂results = [entry for dn, entry in result if isinstance(entry, dict)]

当我尝试执行它时,我可以看到这个 returns 所有 ldap 条目的列表,以及与之关联的相应属性。初始 result 也返回一个列表。有人可以解释一下 results 代码的作用吗?

您所看到的是列表理解。 它们是允许从其他序列构建序列的结构。

在列表理解之前看不到 dn 的原因是它是一个占位符(类似于 for item in list 循环中的 item)。

我不是理解方面的专家,所以我提供了一些链接,可以帮助您更清楚地了解这个问题。

Tutorial: List Comprehensions
Run down of syntax

somelist = [entry for dn, entry in result if isinstance(entry, dict)] 
translates to 

for entry, dn in result:
   if isinstance(entry, dict): # this checks if entry is of type dictionry
      somelist.append(entry)