【问题标题】:Ordered Dictionary and Sorting有序字典和排序
【发布时间】:2017-02-05 15:47:24
【问题描述】:

我正在尝试解决一个简单的练习测试问题:

将 CSV 文件解析为:

  • 仅查找用户在 2010 年 9 月 6 日之前开始的行。
  • 接下来,按升序(按开始日期)对“单词”列中的值进行排序
  • 返回编译后的“隐藏”短语

csv 文件有 19 列和 1000 行数据。其中大部分是无关紧要的。正如问题所述,我们只关心按升序对 start_date 列进行排序,以从“单词”列中获取相关单词。这些词一起会给出“隐藏”的短语。

源文件中的日期是 UTC 时间格式,所以我必须转换它们。我现在处于我认为我已经选择了正确的行的地步,但是我在排序日期时遇到了问题。

这是我的代码:

import csv
from collections import OrderedDict
from datetime import datetime


with open('TSE_sample_data.csv', 'rb') as csvIn:
    reader = csv.DictReader(csvIn)
    for row in reader:

        #convert from UTC to more standard date format
        startdt = datetime.fromtimestamp(int(row['start_date']))
        new_startdt = datetime.strftime(startdt, '%Y%m%d')        

        # find dates before Sep 6th, 2010
        if new_startdt < '20100906':

            # add the values from the 'words' column to a list 
            words = []
            words.append(row['words'])

            # add the dates to a list
            dates = []
            dates.append(new_startdt)

            # create an ordered dictionary to sort the dates... this is where I'm having issues 
            dict1 = OrderedDict(zip(words, dates))
            print dict1
            #print list(dict1.items())[0][1]
            #dict2 = sorted([(y,x) for x,y in dict1.items()])
            #print dict2

当我print dict1 时,我希望有一本有序的字典,其中包含单词和日期作为项目。相反,我得到的是针对创建的每个键值对的多个有序字典。

【问题讨论】:

  • 下次橡皮鸭调试修复它,干脆别发了。其他人不太可能会觉得这很有用。
  • 是的,你当然会! 对你特别有帮助。我的观点是它对您特别有用。遇到同样问题的其他人如何找到这个问题,或者使用您的答案来解决他们的问题,除非他们编写几乎完全相同的代码? SO 是关于创建高质量的问题和答案,请参阅tour。感谢您的努力,我很高兴您解决了您的问题,但这并没有帮助。

标签: python sorting for-loop dictionary ordereddictionary


【解决方案1】:

这是更正的版本:

import csv
from collections import OrderedDict
from datetime import datetime


with open('TSE_sample_data.csv', 'rb') as csvIn:
    reader = csv.DictReader(csvIn)
    words = []
    dates = []
    for row in reader:

        #convert from UTC to more standard date format
        startdt = datetime.fromtimestamp(int(row['start_date']))
        new_startdt = datetime.strftime(startdt, '%Y%m%d')        

        # find dates before Sep 6th, 2010
        if new_startdt < '20100906':

            # add the values from the 'words' column to a list 
            words.append(row['words'])
            # add the dates to a list
            dates.append(new_startdt)

    # This is where I was going wrong! Had to move the lines below outside of the for loop
    # Originally, because I was still inside the for loop, I was creating a new Ordered Dict for each "row in reader" that met my if condition
    # By doing this outside of the for loop, I'm able to create the ordered dict storing all of the values that have been found in tuples inside the ordered dict
    # create an ordered dictionary to sort by the dates
    dict1 = OrderedDict(zip(words, dates))
    dict2 = sorted([(y,x) for x,y in dict1.items()])

    # print the hidden message
    for i in dict2: 
        print i[1]

【讨论】:

  • 而这个答案完全没用。它没有解释问题是什么,你做了什么改变或者这些改变是如何解决它的。同样,当您意识到自己犯了一个小错误时,您可以假设这对 SO 来说不是有用的问答。
猜你喜欢
  • 2014-12-07
  • 2015-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-06
  • 2012-06-16
  • 1970-01-01
  • 2018-01-02
相关资源
最近更新 更多