1.遍歷字典示例1
dict_list = [
{'key': '1'},
{'key': '9670'},
{'key': 'Converse'},
{'key': 'Converse All Star 70 高幫復古黑 1970s 2018新款'},
{'key': '866248'},
{'key': '2018'},
{'key': '162050C'},
{'key': '37900'}
]
def fun(dict_list):
list_1 = [] # 接收value值
list_2 = [] # 接收新的字典
dict_info = {}
for i in range(len(dict_list)):
list_1.append(dict_list[i]["key"])
list_1.sort() # 排序
for i in list_1:
dict_info["key"] = i
print(dict_info)
# 運行的結果是一樣的
list_2.append(dict_info)
# 打印地址
for i in list_2:
print("地址:",id(i))
return list_2
print(fun(dict_list))
運行結果:
地址: 2275698218760
地址: 2275698218760
地址: 2275698218760
地址: 2275698218760
地址: 2275698218760
地址: 2275698218760
地址: 2275698218760
地址: 2275698218760
[{'key': '高幫復古黑 2018新款'}, {'key': '高幫復古黑 2018新款'}, {'key': '高幫復古黑 2018新款'}, {'key': '高幫復古黑 2018新款'}, {'key': '高幫復古黑 2018新款'}, {'key': '高幫復古黑 2018新款'}, {'key': '高幫復古黑 2018新款'}, {'key': '高幫復古黑 2018新款'}]
2.解決方法
因為每次添加的都是同一個內存到list中了,dict_info每次寫入的時候改變了內存中的value,
但是地址是不變,即,創建了一次內存空間,只會不斷的改變value.
完善方法:每次遍歷時候創建一個新的dict_new.
def fun(dict_list):
list_1 = []
list_2 = []
for i in range(len(dict_list)):
list_1.append(dict_list[i]["key"])
list_1.sort() # 排序
for i in list_1:
dict_new = {} # 每次遍歷時創建一個新的內存
dict_new["key"] = i
list_2.append(dict_new)
return list_2
print(fun(dict_list))
運行結果:
地址不相同
地址: 1941366120384
地址: 1941366052616
地址: 1941366052760
地址: 1941366052832
地址: 1941366052904
地址: 1941366052976
地址: 1941366053048
地址: 1941366120384
地址: 1941366120240
[{'key': '1'}, {'key': '162050C'}, {'key': '2018'}, {'key': '37900'}, {'key': '866248'}, {'key': '9670'}, {'key': 'Converse'}, {'key': '高幫復古黑 2018新款'}]
3.遍歷字典示例2
all_items = [] # 放在頁碼上方,會覆蓋數據
# 每頁20個商品
for page in range(0, 20, 20):
print(page)
for product in productList:
itemss ={} # 每次遍歷時創建一個新的內存
itemss["platform"] = 1 # 淘寶 1 京東 2
itemss["gId"] = product.get("spuId") # 商品編號
itemss["brand"] = brand # 商品品牌id
itemss["title"] = product.get("title") # 商品名稱
itemss["soldNum"] = product.get("soldNum") # 銷量
itemss["locations"] = 1 # 所在榜單 1:鞋,2:服裝
itemss["goodNumber"] = product.get("articleNumber") # 商品貨號
itemss["minSalePrice"] = product.get("minSalePrice") # 商品售價
print("items==", itemss)
all_items.append(itemss)
運行結果
4.解決方法
# 每頁20個商品
for page in range(0, 20, 20):
print(page)
all_items = [] # 總列表套字典,要放在遍歷頁碼下方,也不能放在頁碼上方,不然會覆蓋數據.
for product in productList:
itemss ={} # 每次遍歷時創建一個新的內存
itemss["platform"] = 1 # 淘寶 1 京東 2
itemss["gId"] = product.get("spuId") # 商品編號
itemss["brand"] = brand # 商品品牌id
itemss["title"] = product.get("title") # 商品名稱
itemss["soldNum"] = product.get("soldNum") # 銷量
itemss["locations"] = 1 # 所在榜單 1:鞋,2:服裝
itemss["goodNumber"] = product.get("articleNumber") # 商品貨號
itemss["minSalePrice"] = product.get("minSalePrice") # 商品售價
print("items==", itemss)
all_items.append(itemss)
運行結果: