我试着数一数,比如说,整数。我有一个csv文件中的数字列表,我可以读入,它看起来像4245,34,99340,。。。 我要做的是把一本字典还给我键:值对其中键是csv文件中的整数值,值是它在列表中出现的次数。我不知道我在这里做错了什么,如果有任何帮助,我将不胜感激
allCounts = dict()
rows = csv.reader(open('...csv'), delimiter=',')
for intValue in rows:
intVal = intValue[0]
for intVal, numAppearances in allCounts:
if intVal in allCounts:
allCounts[numAppearances] = allCounts[numAppearances]+1
else:
allCounts[numAppearances] = 1
您所做的是遍历每个单元格的整个dict,这有点奇怪,可能不是您想要做的。你真正想做的只是查看dict并增加有问题的键。所以:
最后一行使用了
dict
的一个很好的小特性,如果找不到键,它将返回一个默认值。在在您自己的代码中,有一些值得注意的缺陷。最重要的是第四和第五行。您从所选行提取第一个字段并将其分配给
intVal
,但随后在迭代dict时使用它作为键来完全屏蔽intVal
。这意味着赋值根本不起作用。在if
子句注定失败。您正在检查某个键是否在dict中,但是您通过迭代同一个dict中的键得到了该键。当然,该键在dict中下一个问题是,
else
子句正在修改要迭代的集合。Python不能保证这对dicts是如何工作的,所以不要这样做因此,根本没有理由在dict上迭代,您可以直接获取您感兴趣的任何一个键值对。您应该迭代文件中的整数列表。在
CSV文件的结构总是由一系列值(通常用逗号分隔)构成行,这些行用换行符分隔。CSV模块通过返回列表来保留此视图。要深入到实际值,需要迭代每一行,然后遍历该行中的每个字段。代码迭代每一行,然后迭代dict中每一行的每个键,忽略字段。在
听起来你想要的是一个计数器对象:
http://docs.python.org/library/collections.html#counter-objects
另外,我认为您可能需要使用CSV模块:
http://docs.python.org/library/csv.html
使用内置模块应该会让它更简单:)
要获取行,请执行以下操作:
那么你应该能够做到:
^{pr2}$摆脱
intVal = intValue[0]
因为intValue是一个字符串,所以您将是该数字的字符串表示形式中的第一个字符。你真正想要的是
intValue = int(intValue)
。在那么你的逻辑就完全错了——目前allCounts被初始化为一个空字典,你无法对其进行迭代。您要做的是迭代
csv.reader
返回的值,您已经是了。从那里你的逻辑很接近不幸这既不是马蹄铁也不是手榴弹。你想要的是:相关问题 更多 >
编程相关推荐