【发布时间】:2020-11-23 14:01:55
【问题描述】:
这是我的代码:
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
我希望属性“height”使用 for 循环来表示列表中每个人的位置。我的代码已经根据年龄从最小到最大对列表中的人进行了排序。现在我希望代码使用 for 循环,以便属性 height 为排序列表中的每个人提供他们在列表中的位置,即给出 Anna 1、Hanna 2、Mark 3 和 James 4。
这是我迄今为止尝试过的,但它不起作用:
i = 0
for height in people:
i += 1
people.height = int(i)
people = sorted(people)
return people
有人知道我能做什么吗?
【问题讨论】:
-
你不需要调用 sorted inside loop。您也可以使用 enumerate() 函数在循环中获取索引。(docs.python.org/3/library/…)
标签: python python-3.x list for-loop attributes