如何在对象列表中搜索最小索引

时间:2019-02-11 05:04:07

标签: python python-3.x

我想在对象列表中搜索对象属性中存在的最低编号。

使用列表理解和min函数,这非常容易。当我想找到对象的索引时,问题就来了。

class School:
    def __init__(self, name, num_pupils, num_classrooms):
        self.name = name
        self.num_pupils = num_pupils
        self.num_classrooms = num_classrooms

    def students_per_class(self):
        return self.num_pupils / self.num_classrooms

    def show_info(self):
        print(f"{self.name} has {self.students_per_class():.2f} students per class.")

    def string_checker(question):
        valid = False
        while not valid:
            try:
                response = str(input(question))
                if all(character.isalpha() or character.isspace() for character in response):
                    valid = True
                    return response
                else:
                    print("Enter a string containing no numbers of special characters. ")
            except ValueError:
                print("Enter a string containing no numbers of special characters. ")

    def num_checker(question):
        valid = False
        while not valid:
            try:
                response = int(input(question))
                if (response):
                    valid = True
                    return response
                else:
                    print("Enter an integer containing no letters or special characters. ")

        except ValueError:
            print("Enter an integer containing no letters or special characters. ")

    def new_school():
        school_name = string_checker("School Name: ")
        num_pupils = num_checker("Number of Pupils: ")
        num_classrooms = num_checker("Number of Classrooms: ")
        return School(school_name, num_pupils, num_classrooms)


if __name__ == "__main__":
    schools = []
    school = School("Darfield High School", 900, 37)
    schools.append(school)
    school.show_info()

    for i in range(1):
        schools.append(new_school())

    for school in schools:
        school.show_info()

    print(min(school.students_per_class() for school in schools)) 
    # This works fine and prints the value of the lowest number
    print(schools.index(min(school.students_per_class() for school in schools))) 
    # This doesn't work as it tries to find the index of the value returned
    # from the min function as it should.

4 个答案:

答案 0 :(得分:1)

使用enumerate遍历列表,同时跟踪索引:

var hover = false;
document.getElementById("clickmebtn").addEventListener("mouseover", function( event ) {
 console.log('called on hover'); //just to make sure the function is getting called   
  if(!hover) {
    buttonTL.reversed() ? buttonTL.restart() : buttonTL.reverse();
  }
  hover = true;

  }, false);
document.getElementById("clickmebtn").addEventListener("mouseleave", function( event ) {
 console.log('called on dhjhhhjs'); //just to make sure the function is getting called   
  hover = false;
  buttonTL.reversed() ? buttonTL.restart() : buttonTL.reverse();

  }, false);

min(((i, school.students_per_class()) for i, school in enumerate(schools)), key=lambda x: x[1]) 是一个元组,并使用(i, school.students_per_class())的{​​{1}}参数,我们要求Python查找最小值key,随后将其返回索引。

了解lambda here

答案 1 :(得分:1)

我认为您可能正在寻找np.argmin函数,如果您提供列表作为输入,它将返回最小元素的索引。

在这种情况下为:

import numpy as np 
min_ind = np.argmin([school.students_per_class() for school in schools])
print(schools[min_ind])

答案 2 :(得分:1)

您可以使用min的{​​{1}}参数按索引进行搜索:

key

键提供将被比较的值,而不是实际的序列。在这里,我的序列是index = min(range(len(schools)), key=lambda i: schools[i].students_per_class()) print(schools[index]) ,它只是所有元素的索引。但是,我没有找到最小索引,而是这样做了,以便我们为每个索引range(len(schools))找到schools[i].students_per_class()的最小值。

答案 3 :(得分:1)

如果您希望能够进行比较,请对排序进行排序,直接找到这些项目的最小值/最大值,您可以使用“笨拙”方法。这些方法使您可以重载类中内置的函数。

例如,如果您有这样的课程

class Item:
    def __init__(self, value):
        self.value = value

    def __lt__(self, other):
        return self.value < other.value

    def __eq__(self, other):
        return self.value == other.value

然后您可以创建两个实例并像这样直接比较它们,

A = Item(1)
B = Item(2)

print(A < B) # Prints True

或者如果您有项目列表

items = [A, B]

然后您可以通过

获得最少的商品
min_item = min(items)

或它的索引

min_item_index = items.index(min(items))

尽管仅引用最小项目可能就足够了。