0

我需要能够存储数据,一个是数字,一个是它出现的次数。我有一个 for 循环,它调用一个返回字典的方法:

for x in range(total_holidays):
    t = trial()
    y = y + "\n" + str(x+1) + "," + str(t["brown"]) + "," + str(t["rainbow"]) + "," + str(t["nothing"]) + "," + str(t["days"])
    total += t["days"]
    #print total
    if x%10000 == 0:
        y0.append(y)
        y = ""

基本上我需要计算 t['days'] 发生了多少次,这个数字几乎每次都在变化。如果你想要完整的代码看这里:

https://math.stackexchange.com/questions/193846/how-many-trials-would-you-expect-to-give-you-an-accurate-answer

那么我该怎么做,然后我需要把它全部打印出来。

y是 csv 文件的文本,total 用于计算平均值。


正如 mgilson 建议的那样,我应该使用它吗?

from collections import Counter

a = []
for x in range(total_holidays):
    t = trial()
    y = y + "\n" + str(x+1) + "," + str(t["brown"]) + "," + str(t["rainbow"]) + "," + str(t["nothing"]) + "," + str(t["days"])
    total += t["days"]
    a.append(t['days'])
    #print total
    if x%10000 == 0:
        y0.append(y)
        y = ""
z = Counter(a)
print z

我应该有类似的东西吗?

4

2 回答 2

2

您想要的是collections.Counter类型,一种dict专门用于此类任务的子类型:

import collections
days_occurred = collections.Counter()

for ...:
    t = trial()
    days_occurred[t['days']] += 1

# total is now sum(days_occurred.itervalues())

# you print the counts by iterating over the dict

for days, count in days_occurred.iteritems():
    print "%d: %d" % (days, count)
于 2012-09-13T23:57:14.770 回答
1

您不需要手动构建 CSV 文件。Python 已经为此提供了一个内置模块:

import csv

writer = csv.writer(open('output.csv', 'wb'))

# ...

for x in range(total_holidays):
  t = trial()

  writer.writerow([x + 1, t['brown'], t['rainbow'], t['nothing'], t['days']])
  total += t['days']

除此之外,您的问题到底是什么?

于 2012-09-13T23:50:46.263 回答