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

2024-04-28 12:44:42 发布

您现在位置: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)
     

Tags: key字符串in列表newforvalueitem
3条回答

sortedstr.find一起使用:

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

输出:

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

键已排序,因此我们可以跳过排序

我们可以在" "上拆分键,并在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']]

使用列表理解

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

相关问题 更多 >