在列表Python中构建列表

2024-10-01 04:54:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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可以是多个列表。你知道吗

有什么解决办法吗? 谢谢!你知道吗


Tags: in列表forcloseopenminmaxtimestamp
3条回答

试试这个:

result = []

for a in inputList:
    res = []
    for i in a:
        res.append(i['close'])
    result.append(res)

print(result)

可以使用嵌套列表:

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]]

你可以使用一个简单的列表

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']]

相关问题 更多 >