0

This is my code:

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))

My text file looks like this:

List:
Anna 13
Mark 44
James 80
Hanna 45

I want the attribute "height" to represent each persons position in the list using a for-loop. My code already sorts the people in the list according to their age, from youngest to oldest. Now I want the code to use a for-loop so that the attribute height gives each person from the sorted list their position in the list, i.e. gives Anna number 1, Hanna number 2 , Mark number 3 and James number 4.

This is what I've tried so far but it doesn't work:

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

    return people

Does anyone have an idea for what I could do?

1
  • 1
    You don't need to call sorted inside loop. Also you can use enumerate() function to get index in loop.(docs.python.org/3/library/…) Commented Nov 23, 2020 at 14:08

2 Answers 2

1

To do so you can iterate using loop with range:

for i in range(len(people)):
    # + 1 to start enumeration with 1 instead of 0
    people[i].height = i + 1
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much!
1

As mentioned in the comments, you can use enumerate like below

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.