我正在尝试制作一个非常简单的计数脚本,我想使用defaultdict(我不知道如何使用DefaultDict,所以如果有人可以评论我的代码片段,我将非常感激)
我的目标是获取元素 0 和元素 1,将它们合并成一个字符串,然后计算有多少个唯一字符串...
例如,在下面的数据中,有 15 行由 3 个类、4 个类组成,当合并在一起时,我们只有 3 个唯一的类。第一行的合并数据(忽略标题行)为:Class01CD2
CSV 数据:
uniq1,uniq2,three,four,five,six
Class01,CD2,data,data,data,data
Class01,CD2,data,data,data,data
Class01,CD2,data,data,data,data
Class01,CD2,data,data,data,data
Class02,CD3,data,data,data,data
Class02,CD3,data,data,data,data
Class02,CD3,data,data,data,data
Class02,CD3,data,data,data,data
Class02,CD3,data,data,data,data
Class02,CD3,data,data,data,data
Class02,CD3,data,data,data,data
DClass2,DE2,data,data,data,data
DClass2,DE2,data,data,data,data
Class02,CD1,data,data,data,data
Class02,CD1,data,data,data,data
它的想法是简单地打印出有多少个可用的独特类。 有谁能帮我解决这个问题吗?
问候
- 海福莱克斯
最佳答案
由于您正在处理 CSV 数据,因此可以将 CSV 模块与字典一起使用:
import csv
uniq = {} #Create an empty dictionary, which we will use as a hashmap as Python dictionaries support key-value pairs.
ifile = open('data.csv', 'r') #whatever your CSV file is named.
reader = csv.reader(ifile)
for row in reader:
joined = row[0] + row[1] #The joined string is simply the first and second columns in each row.
#Check to see that the key exists, if it does increment the occurrence by 1
if joined in uniq.keys():
uniq[joined] += 1
else:
uniq[joined] = 1 #This means the key doesn't exist, so add the key to the dictionary with an occurrence of 1
print uniq #Now output the results
输出:
{'Class02CD3': 7, 'Class02CD1': 2, 'Class01CD2': 3, 'DClass2DE2': 2}
注意:假设 CSV 没有标题行 (uniq1,uniq2,三,四,五,六
)。
引用文献:
关于python - 通过合并两列数据来计算有多少个唯一标识符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19888255/