问题
我有一个对象列表。每个对象都有两个属性:“score”和“coordinates”。我需要根据属性找到列表中最大的N个对象。score
我遇到的主要问题是仅使用score
属性对对象进行排序。排序可以是部分的。我只对N个最大的对象感兴趣。
当前解决方案
我目前的方法不是最优雅也不是最有效的。这个想法是创建一个dictionary
of 对象indices
及其score
,然后对分数列表进行排序并使用dictionary
来索引产生最大分数的对象。
这些是步骤:
创建一个列表
scores
。列表的每个元素对应一个对象。也就是说,第一个条目是第一个对象的分数,第二个条目是第二个对象的分数,依此类推。dictionary
使用对象的scores
askey
和对象index
as创建一个value
。使用 a 对分数列表进行排序
heapq
以获得N
最大的对象。使用
dictionary
获取具有最大 的那些对象scores
。list
仅使用N
最高分对象创建一个新对象。
代码片段
这是我的排序功能:
import random
import heapq
# Gets the N objects with the largest score:
def getLargest(N, objects):
# Set output objects:
outobjects = objects
# Get the total of objects in list:
totalobjects = len(objects)
# Check if the total number of objects is bigger than the N requested
# largest objects:
if totalobjects > N:
# Get the "score" attributes from all the objects:
objectScores = [o.score for o in objects]
# Create a dictionary with the index of the objects and their score.
# I'm using a dictionary to keep track of the largest scores and
# the objects that produced them:
objectIndices = range(totalobjects)
objectDictionary = dict(zip(objectIndices, objectScores))
# Get the N largest objects based on score:
largestObjects = heapq.nlargest(N, objectScores)
print(largestObjects)
# Prepare the output list of objects:
outobjects = [None] * N
# Look for those objects that produced the
# largest score:
for k in range(N):
# Get current largest object:
currentLargest = largestObjects[k]
# Get its original position on the keypoint list:
position = objectScores.index(currentLargest)
# Index the corresponding keypoint and store it
# in the output list:
outobjects[k] = objects[position]
# Done:
return outobjects
此片段生成100
用于测试我的方法的随机对象。最后一个循环打印N = 3
随机生成的最大对象score
:
# Create a list with random objects:
totalObjects = 100
randomObjects = []
# Test object class:
class Object(object):
pass
# Generate a list of random objects
for i in range(totalObjects):
# Instance of objects:
tempObject = Object()
# Set the object's random score
random.seed()
tempObject.score = random.random()
# Set the object's random coordinates:
tempObject.coordinates = (random.randint(0, 5), random.randint(0, 5))
# Store object into list:
randomObjects.append(tempObject)
# Get the 3 largest objects sorted by score:
totalLargestObjects = 3
largestObjects = getLargest(totalLargestObjects, randomObjects)
# Print the filtered objects:
for i in range(len(largestObjects)):
# Get the current object in the list:
currentObject = largestObjects[i]
# Get its score:
currentScore = currentObject.score
# Get its coordinates as a tuple (x,y)
currentCoordinates = currentObject.coordinates
# Print the info:
print("object: " + str(i) + " score: " + str(currentScore) + " x: " + str(
currentCoordinates[0]) + " y: " + str(currentCoordinates[1]))
我目前的方法可以完成工作,但必须有一种更Pythonic(更矢量化)的方式来实现相同的目标。我的背景主要是 C++,我还在学习 Python。欢迎任何反馈。
附加信息
最初,我正在寻找类似于 C++ 的std:: nth_element
. 似乎 NumPy 在 Python 中提供了此功能partition
。不幸的是,虽然std::nth_element
支持自定义排序的谓词,但 NumPypartition
不支持。我最终使用了 a heapq
,它可以很好地完成工作并按所需的顺序进行排序,但我不知道基于一个属性进行排序的最佳方式。