1

我正在尝试使用 defaultdict 制作一个非常简单的计数脚本(我无法理解如何使用 DefaultDict,所以如果有人能给我评论一段代码,我将不胜感激)

我的目标是获取元素 0 和元素 1,将它们合并为一个字符串,然后计算有多少个唯一字符串......

例如,在下面的数据中有 15 行包含 3 个类,4 个类 ID,当它们合并在一起时,我们只有 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

它的想法是简单地打印出有多少独特的类可用。谁能帮我解决这个问题?

问候
-Hyflex

4

1 回答 1

1

由于您正在处理 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,three,four,five,six)。

参考:

http://docs.python.org/2/library/stdtypes.html#dict

于 2013-11-10T10:11:29.333 回答