python - 使用 for 循环遍历元组列表和内部元组
问题描述
只是想知道如何遍历元组列表并同时遍历元组中的项目。
# I am able iterate over a list of tuples like this,
fruit_list = [('banana','apple','mango'),('strawberry', 'blueberry','raspberry')]
for fruit_tup in fruit_list:
print(fruit_tup)
#output:
#('banana', 'apple', 'mango')
#('strawberry', 'blueberry', 'raspberry')
# Iterate through the items inside the tuples as so,
for (item1,item2,item3) in fruit_list:
print(item1,item2,item3)
#output:
#banana apple mango
#strawberry blueberry raspberry
# This is incorrect but I tried to iterate over the tuples and the items inside the tuples as so
for fruit_tup,(item1,item2,item3) in fruit_list:
print(fruit_tup,item1,item2,item3)
#required output:
#('banana', 'apple', 'mango') banana apple mango
#('strawberry', 'blueberry', 'raspberry') strawberry blueberry raspberry
关于如何做到这一点的任何想法?
解决方案
你需要一个嵌套循环:
fruit_list = [('banana','apple','mango'),('strawberry', 'blueberry','raspberry')]
for fruit_tup in fruit_list:
for fruit in fruit_tup:
print(fruit, end=' ') # no newline but a single space
print() # now do a newline
印刷:
banana apple mango
strawberry blueberry raspberry
推荐阅读
- tensorflow - AttributeError:“操作”对象在 tf.keras.models.save_model() 中没有属性“_graph”
- image-processing - 在 ResNet50 中对包含 pytorch 中的 10 个类的图像进行分类时遇到此错误。我的代码是:
- python-3.x - 如何让 OneClassSVM 模型更准确?(Scikit-学习)
- c++ - 彩色矩形顶部的 c++ graphics.h 文本
- vba - 是否可以使用 VBA 代码作为 SSRS 中文本框的操作
- elasticsearch - 弹性搜索模糊查询意外结果
- html - 预格式化的文本无法在 iPhone 上正确显示
- python - 广播消息的有效方法是什么?
- ruby-on-rails - 如何从 tstzrange 列中获取 ActiveSupport::TimeWithZone 范围?
- python - Python 不能使用从另一个文件调用的函数