python字典,保留整数计数

2024-10-01 13:40:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着数一数,比如说,整数。我有一个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

Tags: 文件csvin列表for字典数字整数
3条回答

您所做的是遍历每个单元格的整个dict,这有点奇怪,可能不是您想要做的。你真正想做的只是查看dict并增加有问题的键。所以:

# first part stays mostly the same
rows = csv.reader(open("...csv") )

allCounts = {} 

for row in rows:
    for field in row:
        allCounts[field] = allCounts.get(field, 0) + 1

最后一行使用了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

使用内置模块应该会让它更简单:)

要获取行,请执行以下操作:

csvfile = open("example.csv")
dialect = csv.Sniffer().sniff(csvfile.read(1024))
csvfile.seek(0)
reader = csv.reader(csvfile, dialect)

那么你应该能够做到:

^{pr2}$

摆脱intVal = intValue[0]

因为intValue是一个字符串,所以您将是该数字的字符串表示形式中的第一个字符。你真正想要的是intValue = int(intValue)。在

那么你的逻辑就完全错了——目前allCounts被初始化为一个空字典,你无法对其进行迭代。您要做的是迭代csv.reader返回的值,您已经是了。从那里你的逻辑很接近不幸这既不是马蹄铁也不是手榴弹。你想要的是:

# Checks to see if intValue is a key in the dictionary
if intValue in allCounts:
    # If it is then we want to increment the current value
    # += 1 is the idiomatic way to do this
    allCounts[intValue] += 1
else:
    # If it is not a key, then make it a key with a value of 1
    allCounts[intValue] = 1

相关问题 更多 >