擅长:python、mysql、java
<blockquote>
<p><strong>Note</strong>: with the above sample code, it will raise an <code>AttributeError</code>, since a dictionary has no <code>.age</code> attribute. I assume that you use Django objects instead which indeed have attributes if you defined a field.</p>
</blockquote>
<p><code>setattr(..)</code>函数更新对象。大多数更新某些内容的函数都不会返回某些内容(这本身不是真的,但对于许多函数来说,这是成立的)。你知道吗</p>
<p>因此,您的列表只是获取<code>setattr</code>调用的结果。我们可以通过以下方法来规避问题:</p>
<pre><code>new_persons_list=list(map(lambda person: setattr(person, 'number', person.age) <b>or person</b>, persons))</code></pre>
<p>但更合理的做法是,在这里使用<code>for</code>循环来更新对象:</p>
<pre><code>for person in persons:
person.number = person.age</code></pre>