小编use*_*909的帖子

Python填充字符串格式的字符串

假设我有模板来填充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)

请注意,它只返回水果,而不是卧室,因为卧室不在地方的价值.

python format zip dictionary python-itertools

3
推荐指数
1
解决办法
126
查看次数

将元组中的元组与列表合并并转换为dict

我有一个元组元组和一个列表.

 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).

最好的方法是什么?

python dictionary tuples list

-1
推荐指数
1
解决办法
64
查看次数

标签 统计

dictionary ×2

python ×2

format ×1

list ×1

python-itertools ×1

tuples ×1

zip ×1