美文网首页
python实现以list1为key,以list2为value的

python实现以list1为key,以list2为value的

作者: 洛丽塔的云裳 | 来源:发表于2019-11-23 23:31 被阅读0次

给定两个可为空的列表,生成以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优化,待续……

相关文章

网友评论

      本文标题:python实现以list1为key,以list2为value的

      本文链接:https://www.haomeiwen.com/subject/bqpkwctx.html