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

问题描述 投票:-1回答:3

我想根据列表中包含的字符串打印出格式化的字符串。但是,我想打印出格式化的字符串以逗号停止。

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

我将如何实现这一目标?

python python-2.7 list
3个回答
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 

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


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)

0
投票
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))
© www.soinside.com 2019 - 2024. All rights reserved.