if i != 0: ...
而不是只写出变量名:
if i: ...
[{‘name‘: ‘jason‘, ‘dob‘: ‘2000-01-01‘, ‘gender‘: ‘male‘}, {‘name‘: ‘mike‘, ‘dob‘: ‘1999-01-01‘, ‘gender‘: ‘male‘}, {‘name‘: ‘nancy‘, ‘dob‘: ‘2001-02-01‘, ‘gender‘: ‘female‘}]
多行代码:
import copy attributes = [‘name‘, ‘dob‘, ‘gender‘] values = [ [‘jason‘, ‘2000-01-01‘, ‘male‘], [‘mike‘, ‘1999-01-01‘, ‘male‘], [‘nancy‘, ‘2001-02-01‘, ‘female‘] ] l_except = [] d = {} for value in values: #方法一 #for index,v in enumerate(value): #d[attributes[index]] = v #方法二 d = dict(zip(attributes,value)) l_except.append(d) #d.clear() #值得注意的是list,dict是传递引用,如果调用此句下句就会为[{},{},{}] #可以用copy.deepcopy传递学拷贝对象l_except.append(copy.deepcopy(d)) print(l_except)
一行代码处理:
l_except = [{arrt: v[index] for index, arrt in enumerate(attributes)}for v in values] print(l_except) # or l_except = [dict(zip(attributes,v)) for v in values] print(l_except)
参考:
极客时间《Python核心技术与实战》
原文:https://www.cnblogs.com/xiaoguanqiu/p/10930197.html