简体   繁体   English

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

[英]how to convert two unsorted lists into a dictionary in a pythonic way?

I need to convert two unsorted lists into a dictionary.我需要将两个未排序的列表转换为字典。 For example, I have a full name list:例如,我有一个全名列表:

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

And I have a last name list:我有一个姓氏列表:

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

I need to convert these two lists into a dictionary:我需要将这两个列表转换为字典:

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

Notice that length of two lists are not equal.请注意,两个列表的长度不相等。 What's more, some of elements in last name list cannot be found in full_name list.I wrote a python script to complete the task.更重要的是,姓氏列表中的某些元素在full_name列表中找不到。我编写了一个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)

And it works fine.它工作正常。 But when the length of list increases, the program runs slowly.但是当列表长度增加时,程序运行缓慢。 I tried to use dictionary comprehension to solve the problem, but I got syntax errors.我尝试使用字典理解来解决问题,但出现语法错误。 What should i do to write the program in a more pythonic way to improve the speed?我应该怎么做才能以更pythonic的方式编写程序来提高速度?

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)

Output:输出:

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

Use dictionary comprehension for a faster method:使用字典理解来获得更快的方法:

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'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM