Python Class For loop


class Person:
    def __ini‎t__(sel‎f, age):
        self._age = age
    @prop‎‎er‎t‎y
    def age(self):
        return self._a‎g‎e
person‎s = [Pe‎r‎son(20), Pe‎‎r‎s‎o‎n(30), Person‎(19), Pers‎on(17), Per‎son(15), Per‎‎son(25)]  
result = persons[0]
for person in persons:
    if person.age < result.age:
        result = person

有人能给我解释一下,在这个for循环中发生了什么?据我所知,它会检查,如果输入的年龄小于结果,如果是,它会"放"出来。它被放入结果变量中。解决方案是15,但是我们怎么得到它呢?

循环遍历persons列表,然后比较他们的年龄。年龄到结果中人的年龄。开始时的结果被设置为persons[0]或Person(20),如果它找到一个更年轻的人,也就是Person。年龄& lt;结果。年龄增长,结果变成了"人"。所以循环是在查找列表中最年轻的人。

对于这样的事情,有时通过写出正在发生的事情来逐步解决问题更容易。

所以我们知道我们正在使用一个Person对象的列表,这些对象有一个指定的age,我们可以检索。

如果插入已有的内容,则开始循环:

result = persons[0] # first person in the list, Person.age = 20
for person in persons:
   if person.age < result.age:
       result = person.age

迭代1:

result = 20
if 20 < 20: # this is false
    result = 20

迭代2:

result = 20
if 30 < 20: # this is false
    result = 30

迭代3:

result = 20
if 19 < 20: # this is true, result is reassigned
    result = 19

等。对于列表中的所有项。

最新更新