如何跟踪numpy数组元素的索引

时间:2019-04-21 04:16:16

标签: python arrays numpy

我正在尝试使用for循环遍历numpy数组的项目。有没有办法跟踪迭代当前项的索引(除了在循环之前初始化计数器并在循环内递增计数器)?

class Album(db.Model):
    # ...
    @property
    def photographes(self):
        photographes = set()
        for img in self.pictures:
            if img.photographe not in photographes:
                photographes.add(img.photographe)
        return photographes

我想得到的是(请记住,这是一个numpy数组,而不是列表)

version: '3'

services:

client:
  container_name: client
  build:
    context: ./client
    dockerfile: Dockerfile
  volumes:
    - './client:/usr/src/app'
    - '/usr/src/app/node_modules'
  ports:
    - '3000:3000'
  environment:
    - NODE_ENV=development
    - NODE_PATH=src

2 个答案:

答案 0 :(得分:1)

您可以这样迭代:

import numpy as np

a = np.array([6,5,7,0,1,3,4])

for index in range(a.shape[0]):  # use range with nparray.shape[0] to get the size
    print(index) # you can do a[index] to get the value

此输出:

0
1
2
3
4
5
6

答案 1 :(得分:0)

正确的方法是使用enumerate

myArray = [4, 5, 6, 7]

for i,item in enumerate(myArray):
    print(i)