带和的Python列表理解

时间:2016-06-24 15:23:45

标签: python list-comprehension

我有一些看起来像这样的python代码:

Prefix(:=<http://www.semanticweb.org/hilal/ontologies/2016/5/untitled-    ontology-58#>)
Prefix(owl:=<http://www.w3.org/2002/07/owl#>)
Prefix(rdf:=<http://www.w3.org/1999/02/22-rdf-syntax-ns#>)
Prefix(xml:=<http://www.w3.org/XML/1998/namespace>)
Prefix(xsd:=<http://www.w3.org/2001/XMLSchema#>)
Prefix(rdfs:=<http://www.w3.org/2000/01/rdf-schema#>)                
Ontology(<http://www.semanticweb.org/hilal/ontologies/2016/5/untitled- ontology-58>

Declaration(Class(:Shadow))
Declaration(Class(:Test))
Declaration(NamedIndividual(:t1))
Declaration(NamedIndividual(:t2))
Declaration(NamedIndividual(:t3))
Declaration(AnnotationProperty(<http://swrl.stanford.edu/ontologies/3.3/swrla.owl#isRuleEnabled>))



############################
#   Named Individuals
############################

# Individual: :t1 (:t1)

ClassAssertion(:Test :t1)

# Individual: :t2 (:t2)

ClassAssertion(:Test :t2)

# Individual: :t3 (:t3)

ClassAssertion(:Test :t3)


DLSafeRule(Annotation(<http://swrl.stanford.edu/ontologies/3.3/swrla.owl#isRuleEnabled> "true"^^xsd:boolean) Annotation(rdfs:comment ""^^xsd:string) Annotation(rdfs:label "S1"^^xsd:string) Body(BuiltInAtom(<http://swrl.stanford.edu/ontologies/built-ins/3.3/swrlx.owl#makeOWLThing> Variable(<new>) Variable(<x>)) ClassAtom(:Test Variable(<x>)))Head(ClassAtom(:Shadow Variable(<new>))))
)

我不能为我的生活展开这个语法而不使用列表理解让我理解。请协助。

2 个答案:

答案 0 :(得分:3)

直接翻译

mat = [[3], [4], [4], [0], [1, 2]]
nwalls = 5*[1]
for i in range(1, 3):
    _nwalls = []
    for j in range(5):
        tot = 0                # - sum
        for k in mat[j]:       #  /
            tot += nwalls[k]   # /
        _nwalls.append(tot)
    nwalls = _nwalls

(nwalls[k] for k in mat[j])它是一个生成器,在python repl中,你可以将它检查为:

>>> y = (x for x in range(10))
>>> type(y)
<class 'generator'>

sum可以使用sum( (x for x in range(10)) )生成器,而PEP289可以使用

  

如果函数调用具有单个位置参数,则它可以是没有额外括号的生成器表达式,但在所有其他情况下,您必须将其括起来。

所以它看起来像sum(x for x in range(10))

答案 1 :(得分:1)

而不是每次只为列表中的特定插槽分配新值时重新创建nwalls列表,只需保留列表中先前值的记录,这样就不会最终使用生成的值在循环的早期:

mat = [[3], [4], [4], [0], [1, 2]]
nwalls = 5*[1]
prev_nwalls = 5*[1]
for _ in range(1,3):
    for j in range(5):
        nwalls[j] = sum(prev_nwalls[k] for k in mat[j])
    prev_nwalls[:] = nwalls

assert nwalls == [1, 2, 2, 1, 2]

如果你想完全避免理解,首先要知道sum内置的python等同于:

def sum(iterable):
    s = 0
    for n in iterable:
        s+=n
    return s

因此,行nwalls[j] = sum(prev_nwalls[k] for k in mat[j])将替换为:

s = 0
for k in mat[j]:
    s+=nwalls[k]
nwalls[j] = s