請問有人可以幫我從我的元組列表中刪除多余的括號嗎?latest_Value = {"17:00:00": 100.00}Dict1 = {"current value": 100, "stock_purchased": "false", "Historic value": [('16:00:00', 55.50), ("15:00:00", 45.50), ("14:00:00", 75.50),("13:00:00", 65.50), ("12:00:00", 55.50)]}# converting the latest_value into a tupleList_it = [(k, v) for k, v in latest_Value.items()]# insert the tuple into the tuple listDict1['Historic value'].insert(0, List_it)data2 = Dict1["Historic value"]print(data2)#output [[('17:00:00', 100.0)], ('16:00:00', 55.5), ('15:00:00', 45.5), ('14:00:00', 75.5), ('13:00:00', 65.5), ('12:00:00', 55.5)]當列表被修改時,它會添加一個嵌套列表而不僅僅是元組。你如何避免這種情況?
1 回答

長風秋雁
TA貢獻1757條經驗 獲得超7個贊
# converting the latest_value into a tuple List_it = [(k, v) for k, v in latest_Value.items()]
那實際上是錯誤的。這會將整個 dict 轉換為元組,而不僅僅是最后一個鍵值對,因此Dict1['Historic value'].insert(0, List_it)
將整個元組列表添加到Dict1['Historic value']
.
latest_Value
包含單個鍵值對的事實不會改變將List_it
是元組列表的事實。
如果您更改為,Dict1['Historic value'].insert(0, List_it[0])
那么您將獲得所需的輸出。
添加回答
舉報
0/150
提交
取消