<p>这是一个有效的解决方案:</p>
<pre><code>import csv
import collections
data= {}
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 = 'male' if row[5] == 'M' else 'female'
if year_of_joining not in data:
data[year_of_joining]={'male': {f'Q{i + 1}': 0 for i in range(4)}, 'female': {f'Q{i + 1}': 0 for i in range(4)}}
data[year_of_joining][gender][quarter_of_joining] += 1
data = collections.OrderedDict(sorted(data.items())) # sorting
for year in data:
print("Male's and Female's: %s: %s" % (year, data[year]))
</code></pre>
<p>上面代码的唯一区别是,它以稍微不同的格式提供输出,但我怀疑这可能是您首先想要的:</p>
<pre><code>Male's and Female's: 1993: {'male': {'Q1': 0, 'Q2': 0, 'Q3': 0, 'Q4': 1}, 'female': {'Q1': 0, 'Q2': 0, 'Q3': 0,
'Q4': 0}}
Male's and Female's: 1998: {'male': {'Q1': 0, 'Q2': 0, 'Q3': 0, 'Q4': 1}, 'female': {'Q1': 0, 'Q2': 0, 'Q3': 0,
'Q4': 0}}
Male's and Female's: 1999: {'male': {'Q1': 0, 'Q2': 1, 'Q3': 1, 'Q4': 0}, 'female': {'Q1': 0, 'Q2': 0, 'Q3': 0,
'Q4': 1}}
Male's and Female's: 2001: {'male': {'Q1': 0, 'Q2': 0, 'Q3': 0, 'Q4': 0}, 'female': {'Q1': 1, 'Q2': 0, 'Q3': 0,
'Q4': 0}}
Male's and Female's: 2003: {'male': {'Q1': 0, 'Q2': 0, 'Q3': 0, 'Q4': 0}, 'female': {'Q1': 0, 'Q2': 0, 'Q3': 0,
'Q4': 1}}
</code></pre>
<p>如果没有,请告诉我,我会修改它</p>