輸入:
a = [
{'id': 18, 'user_name': '張三', 'gift_name': '禮物9', 'surplus': 10},
{'id': 19, 'user_name': '李四', 'gift_name': '禮物10', 'surplus': 20},
{'id': 20, 'user_name': '王二', 'gift_name': '禮物11', 'surplus': 18},
{'id': 18, 'user_name': '張三', 'gift_name': '禮物10', 'surplus': 2},
{'id': 18, 'user_name': '張三', 'gift_name': '禮物11', 'surplus': 12},
{'id': 19, 'user_name': '李四', 'gift_name': '禮物11', 'surplus': 2}
]
輸出
b = [
{
'id':18,'user_name':'張三',
"gift_info":[{"gift_name":'禮物9','surplus':10},
{"gift_name":'禮物10','surplus':2},
{'gift_name': '禮物11', 'surplus': 12}
]
},
{
'id': 19, 'user_name': '李四',
"gift_info":[{'gift_name': '禮物10', 'surplus': 20},
{'gift_name': '禮物11', 'surplus': 2}]
},
{
'id': 20, 'user_name': '王二',
'gift_info':[{'gift_name': '禮物11', 'surplus': 18},
]
}
]
代碼:
b = [] # 用來存放結果
ids_dict = {} # 用來存放列表中某個id 第一次出現於列表b中的下標
for index, value in enumerate(a):
id_n = value.get('id')
if not ids_dict.get(id_n): # 第一次出現該id,爲防止index爲0 出現get()錯誤,index一開始從1開始
ids_dict[id_n]=index+1 # 記錄當前id的下標
temp = {key: value for key, value in value.items()
if key == 'id' or key == 'user_name'} # 先 生成id 和user_name 的字典,其他字段額外處理
gift_lists = [dict(gift_name=value.get('gift_name'),
surplus=value.get('surplus')
)]
temp['gift_info']=gift_lists
b.append(temp)
else: # 第>=2次出現該id
index=ids_dict.get(id_n)
index-=1 # 還原其原來下標
gift_lists = [dict(gift_name=value.get('gift_name'),
surplus=value.get('surplus')
)]
b[index]['gift_info'].extend(gift_lists)
print(b)
Q&A:
-
ids_dict中的鍵值對中的 值下標從1開始,從0開始會出錯
因爲我判斷id 是否能夠在ids_dict拿到值,如果值是0(下標爲0),name就會判斷它是第一次出現該id,但實際上已經出現過此id -
append和extend的區別
extend 接受一個參數(list類型),並且把這個 list 中的每個元素添加到原 list 中
append 接受的參數可以是任何數據類型,並且簡單地追加到 list 的尾部 -
思路的問題
感覺自己每次在解決一個問題時,剛開始的思路有點兒跑偏(一直在測試自己的想法),後來過分依賴debug功能,而不是自己手寫寫算法流程.在解決這道題時,我花了一些時間用上一題的解法,但實際上,題目不同,解決的方案肯定也不一樣,當然也可以用之前的方法解決,但算法效率就不行了 -
我的測試記錄:
- 利用filter()函數過濾,failed
- 利用my_dict.items() 以
列表形式返回的二元組
,只能遍歷,其他操作無法進行
for i in a:
display(i.items()[1])
# 'dict_items' object does not support indexing
- 字典的zip()函數 —> 將字典的一對鍵作爲二元組
- 通過元組來創建字典,failed —>dict([[],…,[]]) or dict([(),…,()])才成功
- 字典從無序變成有序 —> from collections import OrderedDict,其順序是字典元素的插入順序
- 創建雜交水稻(命名爲列表字典生成式)
x=[{'gift_name': '禮物9', 'id': 18, 'surplus': 10, 'user_name': '張三'},
{'gift_name': '禮物10', 'id': 18, 'surplus': 2, 'user_name': '張三'},
{'gift_name': '禮物11', 'id': 20, 'surplus': 18, 'user_name': '王二'}]
for i in x:
# 直接將其中的key變成字符串,而不是當成變量!!!!!!!!
result=[ dict(key=value) for key,value in i.items() if key=='gift_name']
print(result)
# [{'key': '禮物11'}]
直接將其中的key變成字符串,而不是當成變量
x=[{'gift_name': '禮物9', 'id': 18, 'surplus': 10, 'user_name': '張三'},
{'gift_name': '禮物10', 'id': 18, 'surplus': 2, 'user_name': '張三'},
{'gift_name': '禮物11', 'id': 20, 'surplus': 18, 'user_name': '王二'}]
for i in x:
result=[ {key:value} for key,value in i.items() if key=='id']
print(result)
# [{'id': 20}]
- 字典的創建 her_dict=dict(b=1)
- 列表的淺複製 b=[1,2,[3,6]] a=b[:]
安利 python 代碼執行可視化網站
http://www.pythontutor.com/visualize.html#mode=edit