擅长:python、mysql、java
<p>您可以使用<code>accumulator</code>变量来保存总和和<code>for</code>循环:</p>
<p>以下是一个例子:</p>
<pre class="lang-py prettyprint-override"><code>movies = [
("Titanic", 20000000),
("Dracula", 9000000),
("James Bond", 4500000),
("Pirates of the Caribbean: On Stranger Tides", 379000000),
("Avengers: Age of Ultron", 365000000),
("Avengers: Endgame", 356000000),
("Incredibles 2", 200000000)
]
if __name__ == "__main__":
# Declarative
accumulator = 0
for (_, budget) in movies:
accumulator += budget
print(accumulator / len(movies))
</code></pre>
<p>在<code>for</code>语句中,我将这两个项从元组中展开为两个新变量:<code>_</code>和<code>budget</code>。使用<code>_</code>声明不需要使用该变量是一种常见做法</p>
<p>最后一行打印平均值,计算方法是除以列表长度</p>