我每天都在尝试从学校使用Python的API(一种普通和素食的选择)获取午餐时使用的格式。有时,学校关闭后,清单中只有一项。这是我从api获取的列表的翻译版本:
[[['Closed'],['Pasta Al Carne切丝的牛肉,番茄莎莎酱和磨碎的奶酪','Pasta with ratatouille'],['Pancake with Cottage Cheese and jam','Pancake with Cottage Cheese and jam '],['带冷酱汁煮土豆的鱼片','素食慕斯卡'],['带有面包和经典配饰的汉堡包','带有经典配饰的素食汉堡']]
现在我有以下代码:
"Monday: {}\nTuesday: {}\nWednesday: {}\nThursday: {}\nFriday: {}".format(*lunch)
输出到此:
星期一:[“关闭”]
星期二:['Pasta Al Carne,配以切碎的牛排,番茄莎莎酱和磨碎的 奶酪”,“意大利面食料理鼠王”]
等...
如何每天单独格式化,使其看起来更像这样?
星期一:关闭
星期二:通心粉意面配切碎的牛排,番茄莎莎酱和切碎的 起司。素食:料理鼠王意大利面
星期三:煎饼配白软干酪和果酱。素食主义者:煎饼和干酪和果酱
等...
我一直在寻找如何在Python中格式化列表的方法,但是由于我是新手,所以很难知道要搜索什么。 谢谢!
答案 0 :(得分:1)
这里需要一个简单的MKMapView
:
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))
函数,该函数使您可以使用字符串(在我们的示例中为“,”)作为列表项的分隔符
答案 1 :(得分:0)
zip(* iterables)
zip(iterator1,iterqator2,iterator3 ...)
制作一个迭代器,以聚合每个可迭代对象中的元素。
返回一个元组的迭代器,其中第i个元组包含第i个 每个自变量序列或可迭代对象的元素。迭代器 当最短的输入可迭代耗尽时停止。
午餐= [['已关闭'],['意大利面卡尔恩配牛肉丝,番茄莎莎和磨碎的奶酪','意大利面配料理鼠王》',['煎饼配干酪和果酱','煎饼配干酪和果酱”,[“冷酱煮土豆的鱼片”,“素食慕萨卡”,[带有面包和经典配饰的汉堡包,'带有经典配饰的素食汉堡”]] days = ['Monday','Tuesday','Wednesday','Thursday','Friday']
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