如何在python中将正则表达式的结果添加到字典中?

2024-04-25 17:20:10 发布

您现在位置:Python中文网/ 问答频道 /正文

假设有一段代码查找正则表达式“x是y”并将其存储在某个变量中。一旦你有了它,你怎么把它们以dict = {y:x, y:x, y:x,...}的格式添加到字典里? 示例-“狗是狗”“狐狸是狗”“蓝色是颜色”->;dict ={canine:["dog", "fox"], color:"blue"}


Tags: 代码gt示例字典颜色格式bluedict
2条回答

对于给定的需求,不必使用regex—这有点开销。通过使用带有append()split()list comprehension的内置setdefault()方法,您几乎可以用一行代码来解决任务。你知道吗

input = [ "a dog is a canine", "a fox is a canine", "blue is a color"]
output = {}
[output.setdefault(v, []).append(k) for k,v in (s.split(' is a ') for s in input)]
print(output)

{'color': ['blue'], 'canine': ['a dog', 'a fox']}

如果窗体始终为“x是y”,则可以使用split()。那么只需要检查y是否已经在你的字典中,并相应地添加。检查以下示例:

dict = {}
phrases = ['dog is a canine', 'wolf is a canine', 'blue is a color']
for phrase in phrases:
    x, y = phrase.split(' is a ')
    if y not in dict:
        dict[y] = []
    dict[y].append(x)
print dict

将打印

{'color': ['blue'], 'canine': ['dog', 'wolf']}

相关问题 更多 >