根据键中的位置对列表中的字典值进行排序

vka*_*l11 1 python

我有一个字典,其中的值是来自作为字符串的键的几个子字符串的列表。例如:

d = {"How are things going": ["going","How"], "What the hell" : ["What", "hell"], "The police dept": ["dept","police"]}
Run Code Online (Sandbox Code Playgroud)

并且我想根据列表值在键中出现的位置获取从列表值生成的列表列表。例如在上面的案例中:

output = [["How", "going"], ["What", "hell"], ["police", "dept"]]
Run Code Online (Sandbox Code Playgroud)

我没有找到一种有效的方法来做到这一点,所以我使用了一种hacky方法:

final_output = []
for key,value in d.items():
    if len(value) > 1:
       new_list = []
       for item in value:
          new_list.append(item, key.find(item)) 
       
          new_list.sort(key = lambda x: x[1]) 
       ordered_list = [i[0] for i in new_list] 
       final_ouput.append(ordered_list)
     
Run Code Online (Sandbox Code Playgroud)

Chr*_*ris 6

使用sortedstr.find

[sorted(v, key=k.find) for k, v in d.items()]
Run Code Online (Sandbox Code Playgroud)

输出:

[['How', 'going'],
 ['What', 'hell'], 
 ['police', 'dept']]
Run Code Online (Sandbox Code Playgroud)