给定两个可为空的列表,生成以list1[i]的值为key,以 list2[i] 为value
方式1:
def create_new_dict(lst1, lst2):
""" lst as key, lst2 as val, return dict """
res = {}
length1 = len(lst1)
length2 = len(lst2)
if length1 >= length2:
for i in range(0, length2):
print lst1[i]
res[lst1[i]] = lst2[i]
for i in range(length2, length1):
res[lst1[i]] = None
else:
for i in range(0, length1):
res[lst1[i]] = lst2[i]
return res
方式2:考虑仅与lst1 长度有关
def create_new_dict(lst1, lst2):
""" lst as key, lst2 as val, return dict """
res = {}
for i in range(0, len(lst1)):
if i < len(lst2):
res[lst1[i]] = lst2[i]
else:
res[lst1[i]] = None
return res
方式3:使用三元运算符
def create_new_dict(lst1, lst2):
""" lst as key, lst2 as val, return dict """
res = {}
for index, key in enumerate(lst1):
res[key] = lst2[index] if index < len(lst2) else None
return res
方式4:使用zip,dict优化
def create_new_dict(lst1, lst2):
""" lst as key, lst2 as val, return dict """
res = {}
if len(lst2) < len(lst1):
internal = len(lst1) - len(lst2)
for i in range(0, internal):
lst2.append(None)
res = dict(zip(lst1, lst2))
print "res: ", res
return res
方式5:使用+ 直接拓展lst2
def create_new_dict(lst1, lst2):
""" lst as key, lst2 as val, return dict """
return dict(zip(lst1, lst2 + [None] * (len(lst1) - len(lst2)))) if len(lst2) < len(lst1) else dict(zip(lst1, lst2))
方式6:使用zip,map优化,待续……