Python中文
首页
教程
问答
标签
搜索
登录
注册
从csv文件中以嵌套dict格式分别计算雄性和雌性
回答此问题可获得
20
贡献值,回答如果被采纳可获得
50
分。
<p>这段代码运行良好,它以这种格式打印结果</p> <p><a href="https://i.stack.imgur.com/CFhQZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CFhQZ.png" alt="enter image description here"/></a></p> <p>我需要像这样的嵌套dict格式的结果</p> <pre><code>data = { 'year': { 'male': {'Q1': 1, 'Q2': 1, 'Q3': 1, 'Q4': 1, }, 'female': { 'Q1': 1, 'Q2': 1, 'Q3': 1, 'Q4': 1, } } } </code></pre> <p>守则:</p> <pre><code>import csv results = {'males': {}, 'females': {}} with open('1000 Records.csv') as csv_file: csv_reader = csv.reader(csv_file) for row in csv_reader: year_of_joining = int(row[17]) quarter_of_joining = row[15] gender = 'males' if row[5] == 'M' else 'females' if year_of_joining not in results[gender]: results[gender][year_of_joining] = {f'Q{i + 1}': 0 for i in range(4)} results[gender][year_of_joining][quarter_of_joining] += 1 years = list(results['males'].keys()) + list(results['females'].keys()) years = sorted(list(set(years))) for year in years: count = [results['males'].get(year, 0), results['females'].get(year, 0)] print("Male's and Female's: %s: %s" % (year, count)) </code></pre>
0 条评论
分类:
Python问答
请先
登录
后评论
默认排序
时间排序
1 个回答
匿名
1天前
擅长:python、mysql、java
<p>你很接近。在你的<code>for year in years</code>之外保留一本字典,其中存储年度盘点的运行结果:</p> <pre><code>data = {} for year in years: data[year] = {'male':results['males'].get(year, 0), 'female':results['females'].get(year, 0)} </code></pre>
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
plt.savefig不会覆盖现有文件
10 回答
plt.savefig不保存图像
1 回答
plt.savefig在jupyter笔记本中不起作用
2 回答
plt.savefig在从另一个fi调用时停止工作
1 回答
plt.savefig在调用plt.show之前保存空数字
7 回答
plt.save不创建png文件
9 回答
plt.scatter overlay分类数据帧列
2 回答
Plt.Scatter:如何添加title、xlabel和ylab
4 回答
plt.scatter()绘图与Matplotlib中的plt.plot()绘图类似
4 回答
plt.scatter错误'NoneType'对象在成功运行后没有属性'sqrt'
4 回答
plt.set_title()中的标题字符串有误
4 回答
plt.show()
8 回答
plt.show()不在Jupyter笔记本上渲染任何内容
3 回答
plt.show()不打印plt.plot only plt.scatter
4 回答
plt.show()不显示三维散射图像
5 回答
plt.show()不显示任何内容
1 回答
plt.show()不显示数据,而是保留它供下一个图表使用(spyder)
2 回答
plt.show()使终端挂起
9 回答
plt.show()无法使用此代码
9 回答
plt.show()没有打开新的图形风
2 回答