字典还是单子?

2024-05-19 15:53:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要能够存储数据,一个是数字,一个是它出现的次数。我有一个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[‘天']发生了多少次,数字几乎每次都在变化。如果您想要完整的代码,请看这里:

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

我应该要那样的吗?你知道吗


Tags: inforifholidaysrange数字daystotal
2条回答

您不需要手动构造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']

除此之外,你的问题是什么?你知道吗

您需要的是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)

相关问题 更多 >