如何为Python中rows、columns变量编写符合指定格式的for循环?
解决方案
你可以通过将维度名称与data.shape的数值一一对应来实现需求,不用enumerate,而是用zip把维度名称列表和data.shape的结果配对遍历:
def row_column_number(data): # 定义和shape顺序对应的维度名称列表 dimension_names = ['rows', 'columns'] # 遍历名称与对应数值的配对 for name, value in zip(dimension_names, data.shape): print(f'Number of {name} for the dataset are {value}')
为什么你的原代码输出不符合预期?
你用enumerate(data.shape)得到的是**(索引, 维度值)**的元组(比如(0, 4803)),但你需要的是维度的名称(rows/columns)而非索引,所以输出格式不对。
测试效果
假设data.shape为(4803, 24),运行函数后会输出:
Number of rows for the dataset are 4803 Number of columns for the dataset are 24
扩展说明
如果处理更高维的数据(比如3D数组),只需要在dimension_names里添加对应名称即可,比如['depth', 'rows', 'columns'],循环会自动适配。
内容的提问来源于stack exchange,提问作者Armando Bridena
相关产品推荐
相关产品推荐

