使用列表理解对嵌套的词典列表进行迭代



我有一堆包含气象数据的文本文件。每个文本文件存储半小时的数据,即18000个观测值(行)。总共有48个文件(一整天),我将所有数据存储在以下结构中:

# all_data is a list of dictionaries, len=48 --> each dict represents one file
all_data = [{'time': 0026,
'filename': 'file1.txt',
# all_data['data'] is a list of dictionaries, len=18000
# each dict in all_data['data'] represents one line of corresponding file
'data': [{'x': 1.345, 'y': -0.779, 'z': 0.023, 'temp': 298.11},
{'x': 1.277, 'y': -0.731, 'z': 0.086, 'temp': 297.88},
...,
{'x': 2.119, 'y': 1.332, 'z': -0.009, 'temp': 299.14}]
},
{'time': 0056,
'filename': 'file2.txt',
'data': [{'x': 1.216, 'y': -0648, 'z': 0.881, 'temp': 301.11},
{'x': 0.866, 'y': 0.001, 'z': 0.031, 'temp': 301.32},
...,
{'x': 0.181, 'y': 0.498, 'z': 0.101, 'temp': 300.91}]
},
...
]

现在我需要打开它。我需要按顺序创建一个x(all_data[i]['data'][j]['x'])的所有值的列表,用于绘制。幸运的是,数据已经按顺序存储。

我知道我可以简单地做这样的事情来实现我的目标:

x_list = []
for dictionary in all_data:
for record in dictionary['data']: # loop over list of dictionaries
x_list.append(record['x'])

但为了简单起见,我必须对许多没有在这里列出的变量做类似的事情,我真的不想重写这个循环20次,也不想手工创建20个新列表。

有没有一种方法可以使用列表理解来迭代这样的嵌套数据结构

我做了一个祷告,试着:

[x for x in all_data[i for i in len(all_data)]['data'][j for j in len(all_data[i]['data'])]

这当然不起作用。有什么想法吗?

这是我想要的输出,它只是嵌套列表"data"中"x"的值:

all_x = [1.345, 1.277, ..., 2.119, 1.216, 0.866, ..., 0.181, ...]

提前感谢!

from itertools import chain
[ k['x'] for k in chain.from_iterable([ i['data'] for i in all_data ]) ]

你可以试试这个:

import itertools
all_data = [{'time': 0026, 'filename': 'file1.txt', 'data': [{'x': 1.345, 'y': -0.779, 'z': 0.023, 'temp': 298.11}, {'x': 1.277, 'y': -0.731, 'z': 0.086, 'temp': 297.88}, {'x': 2.119, 'y': 1.332, 'z': -0.009, 'temp': 299.14}]},
{'time': 0056, 'filename': 'file2.txt','data': [{'x': 1.216, 'y': -648, 'z': 0.881, 'temp': 301.11}, {'x': 0.866, 'y': 0.001, 'z': 0.031, 'temp': 301.32},{'x': 0.181, 'y': 0.498, 'z': 0.101, 'temp': 300.91}]}]
x_data = list(itertools.chain.from_iterable([[b["x"] for b in i["data"]] for i in all_data]))
print(x_data)

输出:

[1.345, 1.277, 2.119, 1.216, 0.866, 0.181]

如果你不介意使用Pandas,这可能是实现你想要的东西的好方法。跑步 dataDfList = [pandas.DataFrame(f['data']) for f in all_data] 将生成一个数据帧列表,每个数据帧看起来像: | | temp | x | y | z | |------|--------|-------|--------|--------| | 0 | 298.11 | 1.345 | -0.779 | 0.023 | | 1 | 297.88 | 1.277 | -0.731 | 0.086 | | 2 | 299.14 | 2.119 | 1.332 | -0.009 | 每一个都可以很容易地绘制出来。您也可以使用MultiIndex来实现这一点,例如,通过使用pandas.concat(dataDfList)堆叠数据帧列表

如果我理解正确,您想要的输出是:

  1. 列表
  2. 每个元素都是一个子列表,它是变量x->z,temp的值

不仅仅列出x的值。

这就是你的代码:

values = [row.values() for day in all_data for row in day['data']]

values中的每个项都是一个x->z/temp变量的值列表,或者是一个向量值矩阵。

对于您的上述样本数据,输出为:

[[-0.779, 1.345, 0.023, 298.11], [-0.731, 1.277, 0.086, 297.88], [1.332, 2.119, -0.009, 299.14], [-0.648, 1.216, 0.881, 301.11], [0.001, 0.866, 0.031, 301.32], [0.498, 0.181, 0.101, 300.91]]

对应于CCD_ 7变量。

EDIT:如果要提取一个变量的值,请使用numpy,将输出转换为数组并提取相应的列。

最新更新