【问题标题】:extracting values based on key in a dictionary根据字典中的键提取值
【发布时间】:2014-11-17 20:42:37
【问题描述】:

我有一个包含两列的文本文件:1)第 1 列的格式为 yyyy-mm-dd,2)第 2 列是降水。

目标:仅从第 2 列中提取 4 月、5 月、6 月、7 月和 8 月 (4,5,6,7,8) 的降水原始值。

过程:使用 line.split 从 column-1 的 yyyy-mm-dd 格式中仅提取 mm。

  • 制作字典以获取月份和降水值。
  • 在 dct.items() 中使用 for k,v,然后使用 if 语句从字典中提取对应的月份降水值

问题:我可以从字典项目中成功打印 k,v(月份和降水)。但是,当我使用 if 语句来提取特定月份的降水值时,我得到的是空白数组。我想知道我可以使用 .append 以(1.8,2.1,3.3) 格式获取降水。

代码:

file1 = open("test.txt","r")

Growing=[]
Intermediate=[]
Dormant=[]

for line in file1:
    line2 = line.split()
    WQ = line2[1]
    month = line2[0].split("-")[1]
    dct1={month:WQ}
    for k,v in dct1.items():
        if (k ==4 or k==5 or k==6 or k==7 or k==8):
            Growing.append(dct1 [k])
    print Growing

【问题讨论】:

  • 你应该让我们看看test.txt
  • @goncalopp 我在下面的 test.txt 中展示数据:
  • 2007-02-12 1.8 2007-05-07 0.98 2007-08-22 1.0 2007-11-08 1.5 2008-02-07 0.97 2008-06-18 2.0 2008-08-06 1.8 2008-12-04 1.1 2009-02-18 1.1 2009-05-28 1.8 2009-08-06 1.2 2009-11-12 2.5 2010-03-02 1.1 2010-06-21 2.8 2010-08-24 1.5 2010- 11-10 1.1 2011-02-23 1.1 2011-06-16 1.2 2011-09-13 0.61 2011-11-09 0.82 2012-02-22 1.1 2012-06-18 1.2 2012-08-15 3.2 2012-12- 05 1.1 2013-02-21 1.3 2013-05-22 1.3 2013-08-12 1.4 2013-11-12 3.7
  • 请注意,monthWQ 都是字符串,因为您在此处编写了它们,但您正在将它们与整数进行比较。 ('4' == 4 将返回 False)
  • @Ajean,我该怎么办?

标签: python list dictionary append


【解决方案1】:

更明显的结构是列表字典:

data = collections.defaultdict()

在循环中

data.setdefault( month,[]).append( WQ )

然后您可以通过密钥访问每个月的数据。

也许更简单的方法是使用 numpy.loadtxt,

map = {'jan':1,'feb':2,'mar':3,'apr':4,'may':5} # and the rest
data = numpy.loadtxt("test.txt",dtype = dtype([('month','S4'),('WQ',float)]))

然后选择

data[data['month']=='apr']['WQ']

【讨论】:

  • 将您的代码 data=collections,defaultdict() 合并到我的代码中并尝试打印出来。收到错误消息“data=collections.defaultdict() NameError: name 'collections' is not defined。”代码如下:
  • file1 = open("test.txt","r") Growing=[] Intermediate=[] Dormant=[] for line in file1: line2 = line.split() WQ = line2[ 1] 月 = line2[0].split("-")[1] dct1={month:WQ} data=collections.defaultdct1() 打印数据
  • 我认为您的 dtype 关键字在那里有点不可靠......而且考虑到数据格式(在上面的评论中发布得不好),您最终会得到年份而不是月份。仅供参考!
  • @mdurant 非常感谢您的帮助!我使用 numpy 和 map 使用了你的代码。我收到一条错误消息,提示“NameError: name 'dtype' is not defined”。我必须导入一些东西吗?
  • @mdurant 如 Ajean 所述,将月份更改为 int 得到了答案。但是,我真的很喜欢你使用 numpy 的过程。谢谢!
猜你喜欢
  • 2017-04-09
  • 2022-01-11
  • 2022-12-02
  • 1970-01-01
  • 1970-01-01
  • 2017-02-03
  • 1970-01-01
  • 2011-05-31
  • 2019-10-04
相关资源
最近更新 更多