1. 程式人生 > >18.07.16 例題

18.07.16 例題

app lse urn pre def ext 默認 位置 int

例:

user_list = [{"name":"alex","hobby":"抽煙"},
{"name":"alex","hobby":"喝酒"},
{"name":"alex","hobby":"燙頭"},
{"name":"wusir","hobby":"喊麥"},
{"name":"wusir","hobby":"街舞"}]
==>[{‘name‘: ‘alex‘, ‘hobby_list‘: [‘抽煙‘, ‘喝酒‘, ‘燙頭‘]},
{‘name‘: ‘wusir‘, ‘hobby_list‘: [‘喊麥‘, ‘街舞‘]}]

解題思路: 判斷是否在result裏面存在這個人的信息,如果不存在則新建一個字典,把hobby_list對應的value值放到一個列表中; 如果存在把hobby_list對應的列表加入一個hobby.

解題步驟:

user_list = [{"name":"alex","hobby":"抽煙"},
{"name":"alex","hobby":"喝酒"},
{"name":"alex","hobby":"燙頭"},
{"name":"wusir","hobby":"喊麥"},
{"name":"wusir","hobby":"街舞"}]
result = []
for user in user_list:
for new_user in result:
if new_user["name"] == user["name"]:
new_user.setdefault("hobby_list",[]).append(user["hobby"])
break
else:
dic = {}
dic["name"] = user["name"]
dic["hobby_list"] = [user["hobby"]]
result.append(dic)
print(result)

如果默認值參數是一個可變的數據類型,在調用的時候改變了.在其他位置看到的也跟著改變.

例:

def extendList(val, list=[]):
list.append(val)
return list
list1 = extendList(10)
list2 = extendList(123, [])
list3 = extendList(‘a‘)
print(‘list1=%s‘ % list1)
print(‘list2=%s‘ % list2)
print(‘list3=%s‘ % list3)
==>list1=[10, ‘a‘]
list2=[123]
list3=[10, ‘a‘]

18.07.16 例題