使用 for 循环列出索引 python

List index with for-loops python

这是我的代码:

class People:

    def __repr__(self):
        return f"A('{self.name}', {self.age}, {self.height})"

    def __init__(self, name, age, height):
        self.name = name
        self.age = age
        self.height = height

def sorted_list():
    people = []
    fil = open('peoples.txt', 'r').readlines()

    for i in file:
        i = i.split()
        people.append(People(i[0], (i[1]))
    people.sort(key=lambda a: (a.age, a.name))

我的文本文件如下所示:

List:
Anna 13
Mark 44
James 80
Hanna 45

我希望属性“高度”使用 for 循环来表示每个人在列表中的位置。我的代码已经根据年龄从小到大对列表中的人进行了排序。现在我希望代码使用 for 循环,以便属性 height 为排序列表中的每个人提供他们在列表中的位置,即给 Anna number 1,Hanna number 2,Mark number 3 和 James number 4.

这是我迄今为止尝试过的方法,但它不起作用:

i = 0
    for height in people:
        i += 1
        people.height = int(i)
        people = sorted(people)

    return people

有人知道我能做什么吗?

为此,您可以使用 range:

的循环进行迭代
for i in range(len(people)):
    # + 1 to start enumeration with 1 instead of 0
    people[i].height = i + 1

如评论中所述,您可以像下面这样使用枚举

i = 0 # starting point
for height, people_obj in enumerate(people, i):
    people_obj.height = height
# sort your list people