【问题标题】:List index with for-loops python使用for循环python列出索引
【发布时间】: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

有人知道我能做什么吗?

【问题讨论】:

标签: python python-3.x list for-loop attributes


【解决方案1】:

为此,您可以使用带有range 的循环进行迭代:

for i in range(len(people)):
    # + 1 to start enumeration with 1 instead of 0
    people[i].height = i + 1

【讨论】:

  • 非常感谢!
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多