将午餐分类

2024-05-15 01:30:55 发布

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

我试着用每天在学校吃的午餐,从API(一个普通的&;素食主义者的选择)。有时学校关门时,名单上只有一个项目。下面是我从api得到的列表的翻译版本:

[['Closed'], ['Pasta Al Carne with shredded beef, tomato salsa and grated cheese', 'Pasta with ratatouille'], ['Pancake with cottage cheese and jam', 'Pancake with cottage cheese and jam'], ['Breaded fish fillet with cold sauce boiled potatoes', 'Vegetarian moussaka'], ['Hamburgers with bread and classic accessories',' Vegetarian burgers with classic accessories']]

现在我有这个密码: "Monday: {}\nTuesday: {}\nWednesday: {}\nThursday: {}\nFriday: {}".format(*lunch) 输出到:

Monday: ['Closed']

Tuesday: ['Pasta Al Carne with shredded steak, tomato salsa and grated cheese', 'Pasta with ratatouille']

etc...

我怎样才能把每一天单独格式化,使它看起来更像这样

Monday: Closed

Tuesday: Pasta Al Carne with shredded steak, tomato salsa and grated cheese. Vegetarian: Pasta with ratatouille

Wednesday: Pancake with cottage cheese and jam. Vegetarian: Pancake with cottage cheese and jam

etc...

我已经搜索了一段时间如何在Python中格式化列表,但是由于我是新手,所以很难知道要搜索什么。 谢谢


Tags: andwithalclosedjamcheesesalsapasta
2条回答

zip(*iterables)

zip(iterator1, iterqator2, iterator3 ...)

Make an iterator that aggregates elements from each of the iterables.

Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted.

午餐=[['关闭'],['牛肉丝、番茄沙拉和磨碎奶酪意大利面','鼠尾草意大利面'],['白干酪和果酱煎饼',['白干酪和果酱煎饼'],['冷沙司煮土豆面包鱼片','素食穆萨卡'],['面包和经典配饰汉堡包',“经典配饰素食汉堡”]] 天=['星期一','星期二','星期三','星期四','星期五']

r =list(zip(days, lunch)) # ('Monday', ['Closed']), ('Tuesday', ['Pasta Al Carne with shredded beef, tomato salsa and grated cheese', 'Pasta with ratatouille']), ...
for item in r:
    if 'Closed' not in item[1]: # Check if closed
        print ("{}: {}. Vegeterian: {}".format(item[0], item[1][0], item[1][1]))
    else:
        print ("{}: {}".format(item[0], item[1][0]))

输出:

Monday: Closed
Tuesday: Pasta Al Carne with shredded beef, tomato salsa and grated cheese. Vegeterian: Pasta with ratatouille
Wednesday: Pancake with cottage cheese and jam. Vegeterian: Pancake with cottage cheese and jam
Thursday: Breaded fish fillet with cold sauce boiled potatoes. Vegeterian: Vegetarian moussaka
Friday: Hamburgers with bread and classic accessories. Vegeterian:  Vegetarian burgers with classic accessories

这里需要一个简单的join

data = [['Closed'], ['Pasta Al Carne with shredded beef, tomato salsa and grated cheese', 'Pasta with ratatouille'], ['Pancake with cottage cheese and jam', 'Pancake with cottage cheese and jam'], ['Breaded fish fillet with cold sauce boiled potatoes', 'Vegetarian moussaka'], ['Hamburgers with bread and classic accessories',' Vegetarian burgers with classic accessories']]

lunch = [', '.join(item) for item in data]
print("Monday: {}\nTuesday: {}\nWednesday: {}\nThursday: {}\nFriday: {}".format(*lunch))

这里的技巧是str.join函数,它允许您使用字符串,在我们的例子中是“,”作为列表项的分隔符

相关问题 更多 >

    热门问题