如何在下面的 Python 代碼中使用字典的值作為字串擴展現有串列?
x = [ 'h1', 'h2' ]
y = [ 'h3', 'h4' ]
dict_sample = {'xyz': ['ab', 'bc'], 'mno': ['cd', 'de']}
x.extend(dict_sample.keys()) ---> (Output) ['h1', 'h2', 'xyz', 'mno']
y.extend(dict_sample.values()) ----> (Output) ['h3', 'h4', ['ab', 'bc'], ['cd', 'de']]
但是,如何為第二種情況獲得以下所需的輸出?
['h3', 'h4', '['ab', 'bc']', '['cd', 'de']']
uj5u.com熱心網友回復:
假設所需的輸出看起來像['h3', 'h4', '["ab", "bc"]', '["cd", "de"]'],
其中包括字串化的 json 元素,這是一種方法:
import json
y = [ 'h3', 'h4' ]
dict_sample = {'xyz': ['ab', 'bc'], 'mno': ['cd', 'de']}
y.extend([json.dumps(e) for e in dict_sample.values()])
print(y)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/517894.html
標籤:细绳列表字典核心价值清单
上一篇:優化校驗值
