<p>您可以执行以下操作:</p>
<ol>
<li>将标题行添加到数据中(例如,“Runner、Distance、Country”)。</li>
<li>将其保存到文件(例如log.csv)。</li>
<li><p>在这里用Load-csv函数加载它:<a href="https://github.com/kdavies4/ModelicaRes/blob/master/modelicares/util.py#L676" rel="nofollow">https://github.com/kdavies4/ModelicaRes/blob/master/modelicares/util.py#L676</a>
在那里下载util.py文件并执行以下操作:</p>
<pre><code>from util import load_csv
d = load_csv("log.csv")
</code></pre>
<p>你最终应该得到以下字典:</p>
<pre><code>d = {'Runner': ['A', 'B', 'C', 'A', 'B'], 'Distance': [10, 30, 4, 20, 10], 'Country': ['USA', 'UK', 'IT', 'UK', 'USA']}
</code></pre>
<p>load_csv函数使用csv.reader自动创建一个字典,其中的键以在标题行中找到的条目命名。每个键的字典条目是对应列中的值列表。文件如下:
<a href="http://kdavies4.github.io/ModelicaRes/util.html#modelicares.util.load_csv" rel="nofollow">http://kdavies4.github.io/ModelicaRes/util.html#modelicares.util.load_csv</a>。py文件包含许多其他函数,但您可以安全地删除它们(只要您将<code>import numpy as np</code>放在顶部)。</p></li>
<li><p>运行以下代码计算平均距离:</p>
<pre><code># Create counter dictionaries for the statistics.
from collections import Counter
n_runs = Counter()
totals = Counter()
# Calculate the total distance.
for runner, distance in zip(d['Runner'], d['Distance']):
n_runs[runner] += 1
totals[runner] += distance
# Print the results.
for runner in set(d['Runner']):
print("%s has run %i miles with an average of %g."
% (runner, totals[runner], totals[runner]/float(n_runs[runner])))
</code></pre></li>
</ol>
<p>这将提供您想要的结果,并且如果数据被扩展(按行或列),它应该是灵活的。</p>
<p>凯文</p>