从列表打印格式化的字符串到指定的字符

2024-05-10 19:43:25 发布

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

我想根据列表中包含的字符串打印一个格式化的字符串。但是,我想打印格式化的字符串,以逗号结束。你知道吗

例如: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

我该怎么做呢?你知道吗


Tags: of字符串apple列表eggslistbenedict逗号
3条回答

您将需要一本字典,其中存储每种食物类型所属的名称和可能的食物:

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 

您可以通过添加其他食物类型(键)和相关术语(值列表)来扩展测试数据。你知道吗

list_of_foods = (('fruits',('Apple pie', 'A couple of oranges')), ('poultry', ('Eggs benedict')), ('drinks', ('Chocolate Milkshake')))

print "Shopping list: \n"
for category, food_list in list_of_foods:
    print "".join('{}: {} \n'.format(category, ','.join(food_list))

实际上,您没有存储足够的信息来创建所需的输出。我建议将您的信息存储在字典中,如下所示:

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)

相关问题 更多 >