我是Python新手。如何将以下数据作为列表存储在另一个列表中?
inputList = [[{'timestamp': '2017-10-28T00:00:00.000Z', 'open': '0.051430', 'close': '0.051210', 'min': '0.050583', 'max': '0.051955', 'volume': '30953.184', 'volumeQuote': '1584.562468339'}, {'timestamp': '2017-10-29T00:00:00.000Z', 'open': '0.051191', 'close': '0.049403', 'min': '0.048843', 'max': '0.053978', 'volume': '42699.215', 'volumeQuote': '2190.567660769'}],[{'timestamp': '2017-10-28T00:00:00.000Z', 'open': '0.063390', 'close': '0.072991', 'min': '0.062544', 'max': '0.073524', 'volume': '199636.573', 'volumeQuote': '13427.870355674'}, {'timestamp': '2017-10-29T00:00:00.000Z', 'open': '0.072840', 'close': '0.073781', 'min': '0.069449', 'max': '0.090833', 'volume': '284448.623', 'volumeQuote': '21687.962221794'}]]
输出应为:
outputList = [[0.051210, 0.049403],[0.072991, 0.073781]]
到目前为止我所拥有的是:
[0.051210, 0.049403, 0.072991, 0.073781]
我使用以下代码:
insideLoop = []
outputList = []
for list in inputList:
for i, v in enumerate(list):
closing = float(v['close'])
insideLoop.append(closing)
outputList.append(insideLoop)
需要注意的是,inputList可以是多个列表。
对此有何解决方案? 非常感谢!
答案 0 :(得分:4)
您可以使用简单的列表理解
result = [[x['close'], y['close']] for x, y in inputList]
print(result)
# - > [['0.051210', '0.049403'], ['0.072991', '0.073781']]
<强>更新强>
对于子列表中未确定数量的元素,请使用嵌套列表推导
result = [[x['close'] for x in y] for y in inputList]
print(result)
# - > [['0.051210', '0.049403'], ['0.072991', '0.073781']]
答案 1 :(得分:2)
您可以使用嵌套列表解析:
s = [[{'timestamp': '2017-10-28T00:00:00.000Z', 'open': '0.051430', 'close': '0.051210', 'min': '0.050583', 'max': '0.051955', 'volume': '30953.184', 'volumeQuote': '1584.562468339'}, {'timestamp': '2017-10-29T00:00:00.000Z', 'open': '0.051191', 'close': '0.049403', 'min': '0.048843', 'max': '0.053978', 'volume': '42699.215', 'volumeQuote': '2190.567660769'}],[{'timestamp': '2017-10-28T00:00:00.000Z', 'open': '0.063390', 'close': '0.072991', 'min': '0.062544', 'max': '0.073524', 'volume': '199636.573', 'volumeQuote': '13427.870355674'}, {'timestamp': '2017-10-29T00:00:00.000Z', 'open': '0.072840', 'close': '0.073781', 'min': '0.069449', 'max': '0.090833', 'volume': '284448.623', 'volumeQuote': '21687.962221794'}]]
new_s = [[float(i['close']) for i in b] for b in s]
输出:
[[0.051210, 0.049403], [0.072991, 0.073781]]
答案 2 :(得分:0)
试试这个:
result = []
for a in inputList:
res = []
for i in a:
res.append(i['close'])
result.append(res)
print(result)