我目前有一個字串串列,我試圖將每個字串項創建到字典物件中并將其存盤在串列中。
在嘗試創建此字典串列時,我反復創建了一個大字典,而不是逐項迭代。
我的代碼:
clothes_dict = [{clothes_list[i]: clothes_list[i 1] for i in range(0, len(clothes_list), 2)}]
錯誤(所有專案被合并到一個字典中):
clothes_dict = {list: 1} [{'name': 'Tom', 'age': 10}, {'name': 'Mark', 'age': 5}, {'name': 'Pam', 'age': 7}]
0 = {dict: 2} {'name': 'Tom', 'age': 10}, {dict: 2} {'name': 'Mark', 'age': 5}, {'name': 'Pam', 'age': 7}```
目標輸出(在單個串列中將所有專案創建到單獨的字典中):
clothes_dict = {list: 3} [{'name': 'Tom', 'age': 10}, {'name': 'Mark', 'age': 5}, {'name': 'Pam', 'age': 7}]
0 = {dict: 2} {'name': 'Tom', 'age': 10}
1 = {dict: 2} {'name': 'Mark', 'age': 5}
2 = {dict: 2} {'name': 'Pam', 'age': 7}```
我試圖使串列中的每個條目成為與目標輸出影像形式相同的新字典。
uj5u.com熱心網友回復:
clothes_dict = [{clothes_list[i]: clothes_list[i 1]} for i in range(0, len(clothes_list), 2)]
您在串列理解中錯誤地放置了右大括號 '}' 并將其放在末尾,這意味著您正在執行字典理解而不是串列理解,每個專案都是字典。
uj5u.com熱心網友回復:
您的代碼使用單個字典創建一個串列:
clothes_dict = [{clothes_list[i]: clothes_list[i 1] for i in range(0,l en(clothes_list), 2)}]
如果您(出于某種原因)想要一個包含單個條目的詞典串列:
clothes_dict = [{clothes_list[i]: clothes_list[i 1]} for i in range(0,l en(clothes_list), 2)]
然而,在我看來,這可能是一個 XY 問題——在什么情況下,單項詞典串列是所需的格式?例如,為什么不使用元組串列?
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/368101.html
