遍历numpy数组的最后一个维度

时间:2018-11-24 21:16:46

标签: python arrays python-3.x numpy iteration

请考虑以下代码段:

a = np.ones((2,2,2,2,2))
for example in a:
    for row in example:
        for col in row:
            for box in col:
                print (box.shape)

嵌套for太多,使得代码非常难看。

仅一次显式迭代如何获得相同的效果?

1 个答案:

答案 0 :(得分:1)

重塑数组:

render() {
    const {classes} = this.props
    return (
      <Paper className={classes.root} elevation={4}>
        <Typography type="title" className={classes.title}>
          All Users
        </Typography>
        <List dense>
         {this.state.users.map((item, i) => {
          const photoUrl = item._id
              ? `/api/users/photo/${item._id}?${new Date().getTime()}`
              : '/api/users/defaultphoto'
          return <Link to={"/user/" + item._id} key={i}>
                    <ListItem button>
                      <ListItemAvatar>
                        <Avatar src={photoUrl} className={classes.bigAvatar}/>
                      </ListItemAvatar>
                      <ListItemText primary={item.name}/>
                      <ListItemSecondaryAction>
                      <IconButton>
                          <ArrowForward/>
                      </IconButton>
                      </ListItemSecondaryAction>
                    </ListItem>
                 </Link>
               })
             }
        </List>
      </Paper>
    )
  }
}

一般解决方案:

for box in a.reshape(16,2):
    print(box.shape)

,它将始终在for box in a.reshape(np.prod(a.shape[:-1]), a.shape[-1]): print(box.shape) 的最后一个维度上进行迭代。