Я пытаюсь отформатировать список с обедом в моей школе каждый день, который я получаю от API (один нормальный и вегетарианский вариант) в Python. Иногда в списке будет только один пункт, когда школа закрыта. Вот переведенная версия списка, который я получаю от 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, но, поскольку я новичок, довольно сложно понять, что искать. Спасибо!






Здесь вам нужен простой 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, которая позволяет вам использовать строку, в нашем случае «,», в качестве разделителя для элементов списка.
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.
обед = [['Закрыто'], ['Паста Аль Карне с рубленой говядиной, томатной сальсой и тертым сыром', 'Паста с рататуем'], ['Блинчик с творогом и джемом', 'Блинчик с творогом и джемом' ], ['Рыбное филе в панировке с отварным картофелем в холодном соусе', 'Вегетарианская мусака'], ['Гамбургеры с хлебом и классическими принадлежностями', 'Вегетарианские бургеры с классическими принадлежностями']] days = ['Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница']
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
Фактически вы получаете список списков.