亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何展平包含具有不同數量詞典的列表的列表?

如何展平包含具有不同數量詞典的列表的列表?

翻閱古今 2023-06-20 16:44:16
我有如下的 python 代碼:import numpy as npimport multiprocessing as mpdef func(first, sec):    results = []    for x in range(first):        result_dict = {"a": x, "b": x**sec, "c": x/sec}        results.append(result_dict.copy())    return resultswith mp.Pool(mp.cpu_count()) as pool:    res = pool.starmap(func, [(a, 8) for a in range(1, 4)])然后我res用這段代碼展平了:res = np.asarray(res)res = res.reshape(-1)res = np.array(res).tolist()之后,當我打印res輸出時,如下所示:[[{'a': 0, 'b': 0, 'c': 0.0}], [{'a': 0, 'b': 0, 'c': 0.0}, {'a': 1, 'b': 1, 'c': 0.125}], [{'a': 0, 'b': 0, 'c': 0.0},  {'a': 1, 'b': 1, 'c': 0.125},  {'a': 2, 'b': 256, 'c': 0.25}]]但我希望輸出是這樣的:[{'a': 0, 'b': 0, 'c': 0.0}, {'a': 0, 'b': 0, 'c': 0.0}, {'a': 1, 'b': 1, 'c': 0.125}, {'a': 0, 'b': 0, 'c': 0.0}, {'a': 1, 'b': 1, 'c': 0.125}, {'a': 2, 'b': 256, 'c': 0.25}]您知道如何更改代碼以獲得所需的結果嗎res?
查看完整描述

2 回答

?
泛舟湖上清波郎朗

TA貢獻1818條經驗 獲得超3個贊

of庫允許您將chain.from_iterableitertools列表鏈接到一個列表。

import itertools


res = [[{'a': 0, 'b': 0, 'c': 0.0}],

?[{'a': 0, 'b': 0, 'c': 0.0}, {'a': 1, 'b': 1, 'c': 0.125}],

?[{'a': 0, 'b': 0, 'c': 0.0},

? {'a': 1, 'b': 1, 'c': 0.125},

? {'a': 2, 'b': 256, 'c': 0.25}]]



print(list(itertools.chain.from_iterable(res)))


查看完整回答
反對 回復 2023-06-20
?
楊魅力

TA貢獻1811條經驗 獲得超6個贊

正如在您的示例中,您將字典存儲在列表列表中,列表理解也有效:


res = [[{'a': 0, 'b': 0, 'c': 0.0}],

 [{'a': 0, 'b': 0, 'c': 0.0}, {'a': 1, 'b': 1, 'c': 0.125}],

 [{'a': 0, 'b': 0, 'c': 0.0},

  {'a': 1, 'b': 1, 'c': 0.125},

  {'a': 2, 'b': 256, 'c': 0.25}]]


flat_res = [item for items in res for item in items]

輸出

print(flat_res)

# [{'a': 0, 'b': 0, 'c': 0.0}, {'a': 0, 'b': 0, 'c': 0.0}, {'a': 1, 'b': 1, 'c': 0.125}, {'a': 0, 'b': 0, 'c': 0.0}, {'a': 1, 'b': 1, 'c': 0.125}, {'a': 2, 'b': 256, 'c': 0.25}]



查看完整回答
反對 回復 2023-06-20
  • 2 回答
  • 0 關注
  • 147 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號