【发布时间】: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