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

时间:2020-08-28 05:52:14

标签: python

我有一本字典,其中的值是键(是字符串)中的一些子字符串的列表。 例如:

d = {"How are things going": ["going","How"], "What the hell" : ["What", "hell"], "The police dept": ["dept","police"]}

,我想获得一个列表列表,该列表是根据列表值在键中出现的位置根据列表值生成的。例如,在上述情况下:

output = [["How", "going"], ["What", "hell"], ["police", "dept"]]

我没有找到一种有效的方法,所以我使用了一种怪异的方法:

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)
     

4 个答案:

答案 0 :(得分:6)

sortedstr.find一起使用:

[sorted(v, key=k.find) for k, v in d.items()]

输出:

[['How', 'going'],
 ['What', 'hell'], 
 ['police', 'dept']]

答案 1 :(得分:0)

键已经排序,所以我们可以跳过排序

我们可以在" "上拆分键,并过滤dict中按关联值拆分的键

d = {"How are things going": ["going","How"], "What the hell" : ["What", "hell"], "The police dept": ["dept","police"]}

lists = []
for k in d.keys():
    to_replace = k.split(" ")
    replaced = filter(lambda x: x in d[k],to_replace)
    lists.append(list(replaced))

print(lists)

输出:

[['How', 'going'], ['What', 'hell'], ['police', 'dept']]

答案 2 :(得分:0)

使用列表理解

output = [[each_word for each_word in key.split() if each_word in value] for key, value in d.items()]

答案 3 :(得分:0)

尝试这个。

output = [list(set(k.split()) & set(d.get(k))) for k in d.keys()]
print(output)

# [["How", going"], ["What,"hell"], ["police,dept"]]