简体   繁体   English

如何读取CSV文件以仅将最新的三个值放入字典中?

[英]How can I read a CSV file to only get the most recent three values into a dictionary?

This code reads every row from a CSV file. 此代码从CSV文件读取每一行。 The first column is made to a value in the dictionary. 第一列是字典中的值。 I want to limit the value of the keys to three (with the most recent three values.) 我想将键的值限制为三个(最近的三个值)。

 for row in reader:
        key = row[0]
        if key in result:
        # if the key is in dictionary
            result[key].append(row[1])
            # add what ever is in column 2 to that key
            if len(result[key]) > 3:
            # if the result is three !!
                print ("too long")
                lastThreeValues = (result[key][-3]).copy()
                result[key].clear()
                result[key] = (lastThreeValues)

        else:
            result[key] = [row[1]]

The working code is this 工作代码是这个

reader = csv.reader(open("class1.csv"))
result = {}
for row in reader:
    key = row[0]
    if key in result:
        result[key].append(row[1])
        if len(result[key]) > 3:
            result[key] = (result[key][-3:])

This is much more complicated than you actually need it to be, you can just use slicing to remove the first element. 这比您实际需要的要复杂得多,您可以使用切片来删除第一个元素。

>>> a
[0, 1, 2, 3]
>>> a = a[1:]
>>> a
[1, 2, 3]

All I'm doing is telling it to set the list to equal itself from index 1 to the end. 我正在做的就是告诉它将列表设置为从索引1到末尾相等。 So essentially that's cutting out the first element of the list, which is your oldest value. 所以从本质上讲,这是切出列表的第一个元素,这是您最早的值。

Though as jonrsharpe points out in the comment, using a[-3:] is neater as it literally means the last three elements in the list. 尽管正如jonrsharpe在评论中指出的那样,但使​​用a [-3:]更整洁,因为它字面意思是列表中的最后三个元素。

>>> a = a[-3:]
>>> a
[1, 2, 3]

You could use a collections.deque to greatly simplify the creation of the results dictionary. 您可以使用collections.deque大大简化results字典的创建。 The only complication is that you might would need to convert all its values into list s afterwards, but it can be done with one line of code. 唯一的麻烦是您可能需要在之后将其所有值转换为list ,但是可以用一行代码来完成。

Here's what I mean: 这就是我的意思:

from collections import deque
MAXLEN = 3

for row in reader:
    key = row[0]
    if key in result:
        result[key].append(row[1])
    else:
        result[key] = deque([row[1]], MAXLEN)

# convert result values into lists
result = {k: list(v) for k, v in result.iteritems()}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM