我有一个字典,其中的值是来自作为字符串的键的几个子字符串的列表。例如:
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)
使用sorted有str.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)
| 归档时间: |
|
| 查看次数: |
49 次 |
| 最近记录: |