我想根据列表中包含的字符串打印出格式化的字符串。但是,我想打印出格式化的字符串以逗号停止。
示例:a = ['Apple pie, A couple of oranges, Eggs benedict, Chocolate Milkshake']
我希望我的格式化字符串看起来像这样:
Shopping list:
Fruits: Apple pie, A couple of oranges
Poultry: Eggs benedict
Drinks: Chocolate Milkshake
我将如何完成这项工作?
答案 0 :(得分:4)
您需要一本字典存储每种食物类型所属的名称和可能的食物项目:
testing = {'Fruits':['apple', 'oranges'], 'Poultry':['eggs'], 'Drinks':['Chocolate']}
a = ['Apple pie, A couple of oranges, Eggs benedict, Chocolate Milkshake']
a = a[0].split(', ')
final_data = "Shopping list:\n{}".format('\n'.join('{}: {}'.format(h, ', '.join(i for i in a if any(c.lower() in i.lower() for c in b))) for h, b in testing.items()))
输出:
Shopping list:
Fruits: Apple pie, A couple of oranges
Poultry: Eggs benedict
Drinks: Chocolate Milkshake
您可以通过添加其他食物类型(键)和相关术语(值列表)来扩展测试数据。
答案 1 :(得分:2)
实际上,您没有存储足够的信息来创建您正在寻找的输出。我建议将您的信息存储在字典中,如下所示:
foods = {
'Fruits': ['Apple pie', 'A couple of oranges'],
'Poultry': ['Eggs benedict'],
'Drinks': ['Chocolate Milkshake']
}
然后,您将获得创建所需输出所需的所有信息,如下所示:
output = 'Shopping list:\n'
for category in foods:
category_str = ''
for food in foods[category]:
category_str += '{}, '.format(food)
category_str = category_str[:-2] # cut off trailing comma and space
output += '{}: {}\n'.format(category, category_str)
output = output[:-1] # cut off trailing newline
print(output)
答案 2 :(得分:0)
SELECT c.id FROM c WHERE <filter>