假设我有模板来填充dict中的值:
我有这样的模板:
templates = [
"I have four {fruit} in {place}",
"I have four {fruit} and {grain} in {place}",
...
]
Run Code Online (Sandbox Code Playgroud)
使用这样的字典:
my_dict = {'fruit': ['apple', 'banana', 'mango'],
'place': ['kitchen', 'living room'],
'grain' : ['wheat', 'rice']
}
Run Code Online (Sandbox Code Playgroud)
说我有这样一句话:
sentence = "I have four apple in kitchen"
Run Code Online (Sandbox Code Playgroud)
鉴于这句话,模板和字典,我想知道该句子匹配其中一个模板并返回它匹配的值,如下所示:
{'fruit': 'apple', 'place': 'kitchen'}
Run Code Online (Sandbox Code Playgroud)
和上面类似,如果:
Input: "I have four apple and wheat in kitchen"
Output: {'fruit': 'apple', 'grain': 'wheat', 'place': 'kitchen'}
Run Code Online (Sandbox Code Playgroud)
如果能够处理这个问题会很棒:
Input: "I have four apple in bedroom"
Output: {'fruit': 'apple'}
Run Code Online (Sandbox Code Playgroud)
请注意,它只返回水果,而不是卧室,因为卧室不在地方的价值.
我有一个元组元组和一个列表.
data = ((1, 'a', 'a1'), (2, 'b', 'b2'), (3, 'c', 'c2'))
names = ['number', 'character', 'numchar']
Run Code Online (Sandbox Code Playgroud)
我怎么能让它看起来像这样?
my_dict = {'number': [1, 2, 3], 'character': ['a','b','c'], 'numchar': ['a1','b2','c2']}
Run Code Online (Sandbox Code Playgroud)
len(data)可能会有所不同len(names),但len(data[0])总会相等len(names).
最好的方法是什么?