如何以python的方式将两个未排序的列表转换为字典?

fivyi3re  于 2021-09-08  发布在  Java
关注(0)|答案(2)|浏览(392)

我需要将两个未排序的列表转换成一个字典。例如,我有一个全名列表:

full_name = ['taylor/swift', 'lady/gaga', 'leborn/james', 'james/harden']

我有一个姓氏列表:

last_name = ['harden', 'james', 'swift', 'smith']

我需要将这两个列表转换为字典:

{'harden':'james/harden', 'james':'leborn/james', 'swift':'taylor/swift'}

请注意,两个列表的长度不相等。此外,姓氏列表中的一些元素在全名列表中找不到。我编写了一个python脚本来完成这项任务。

def index_match(full_index, last_index):
    last_valid = [s for s in last_index if any(s in xs for xs in full_index)]
    matcher = []
    for s in last_valid:
        for xs in full_index:
            if s in xs:
                matcher.append(xs)
                break
    return dict(zip(last_valid, matcher))

matcher = index_match(full_name, last_name)

for item in matcher.items():
    print(item)

而且效果很好。但当列表长度增加时,程序运行缓慢。我试图用字典理解来解决这个问题,但我遇到了语法错误。我应该怎么做才能以一种更具python风格的方式编写程序来提高速度?

fv2wmkja

fv2wmkja1#

full_name = ['taylor/swift', 'lady/gaga', 'leborn/james', 'james/harden']
last_name = ['harden', 'james', 'swift', 'smith']

out = {l:f for l in last_name for f in full_name if f.split("/")[1] == l}
print(out)

输出:

{'harden': 'james/harden', 'james': 'leborn/james', 'swift': 'taylor/swift'}
jrcvhitl

jrcvhitl2#

使用字典理解可获得更快的方法:

full_name = ['taylor/swift', 'lady/gaga', 'leborn/james', 'james/harden']
last_name = ['harden', 'james', 'swift', 'smith']
last_name_to_full_name = {f.split(r'/')[1]: f for f in full_name}
last_name_to_full_name = {L: last_name_to_full_name[L] for L in last_name
                          if L in last_name_to_full_name}
print(last_name_to_full_name)

# {'harden': 'james/harden', 'james': 'leborn/james', 'swift': 'taylor/swift'}

相关问题