我有一个字典,其中的值是键中的几个子字符串的列表,它是一个字符串。 例如:
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)
将
sorted
与str.find
一起使用:输出:
键已排序,因此我们可以跳过排序
我们可以在
" "
上拆分键,并在dict中过滤按关联值拆分的键输出:
使用列表理解
相关问题 更多 >
编程相关推荐