我正在尝试用我每天从 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']]
现在我有这段代码: “星期一:{}\n星期二:{}\n星期三:{}\n星期四:{}\n星期五:{}”.format(*午餐) 输出到这个:
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 函数,它允许您使用字符串(在我们的例子中是“,”)作为列表项的分隔符
