如何在Python中解包元组并打印商品所在区域的指定格式信息?
解决方案
你的shopping_list里每个元组的第一个元素是商品所属区域,后续元素是该区域下的具体商品。要实现需求,需要两层遍历:先拿到每个区域的元组,再遍历元组内的商品并结合区域信息输出。
正确代码如下:
shopping_list = [("fruits",'apple','peach'),('dairy','cheese','milk')] for section, *items in shopping_list: for item in items: print(f"You can find the {item} in the {section} section")
代码说明
section, *items是Python的解包语法:将元组第一个元素赋值给section(区域名),把元组剩余所有元素打包为列表赋值给items(该区域的商品集合),这种写法能适配任意数量商品的区域元组。- 内层循环遍历
items,逐个输出每个商品对应的区域提示信息。
运行后输出结果:
You can find the apple in the fruits section You can find the peach in the fruits section You can find the cheese in the dairy section You can find the milk in the dairy section
内容的提问来源于stack exchange,提问作者alper_55
相关产品推荐
相关产品推荐

