假设我有一个球员名单
listOfPlayers = [
("Player1","PG",Cost,projectedPoints),
("Player2","PG",Cost,projectedPoints),
("Player3","SG",Cost,projectedPoints),
("Player4","SG",Cost,projectedPoints),
("Player5","SF",Cost,projectedPoints),
("Player6","SF",Cost,projectedPoints),
("Player7","PF",Cost,projectedPoints),
("Player8","PF",Cost,projectedPoints),
("Player9","C",Cost,projectedPoints),
("Player10","C",Cost,projectedPoints)
]
然后是一个空列表
selectedList = []
我需要按位置对玩家进行排序,并将最佳成本/投射点数比率输入到所选列表中,但抓住的是我每个位置只能有1个,例如(pg,sg,sf,pf , C)。我该怎么做?
答案 0 :(得分:0)
首先按成本/预计分数比例排序:
listOfPlayers.sort(key=lambda (name, pos, cost, pts): float(cost)/pts, reverse=True)
然后遍历列表并将其拉出:
results = {}
for name, pos, cost, pts in listOfPlayers:
if pos in results:
#position already filled
continue
results[pos] = (name, pos, cost, pts)
您可能希望提前停止,具体取决于您是否知道提前需要的位置,例如:
needed_positions = set(["PG", "SG", "SF", "C"])
results = {}
for name, pos, cost, pts in listOfPlayers:
if not needed_positions:
#all spots filled
break
if pos in results:
#this position already filled
continue
results[pos] = (name, pos, cost, pts)
needed_positions.remove(pos)
答案 1 :(得分:0)
players.sort(operator.itemgetter(1)) # sort by position
for pos, players in itertools.groupby(players, key=operator.itemgetter(1)):
best = max(players, key=lambda p:float(p[2])/p[3])
print "The best player for position %s is %s" %(best[1], best[0])
答案 2 :(得分:0)
import itertools
players = [
# name position cost projected_points
("Player1", "PG", 1, 13),
("Player2", "PG", 2, 54),
("Player3", "SG", 4, 44),
("Player4", "SG", 8, 34),
("Player5", "SF", 3, 14),
("Player6", "SF", 2, 91),
("Player7", "PF", 10, 20),
("Player8", "PF", 4, 32),
("Player9", "C", 9, 12),
("Player10", "C", 3, 82)
]
def cost(p):
return float(p[3]) / p[2]
players.sort(reverse=True, key=lambda x: (x[1], cost(x)))
for k, g in itertools.groupby(players, lambda x: x[1]):
best = list(g)[0]
print(best)
答案 3 :(得分:0)
如果您对使用Pandas DataFrame对象执行此操作感兴趣,则此代码可以正常工作。如果您最终需要经常执行这些类型的排序/聚合操作或更大的数据,这将非常有用 - 并且它使用高效的NumPy数组操作来快速执行计算。
df = pandas.DataFrame(listOfPlayers,
columns=["Player", "Pos", "Cost", "ProjectedPoints"])
df['Ratio'] = df.Cost / df.ProjectedPoints
best_players = df.groupby("Pos").apply(lambda x: x.Player.values[x.Ratio.argmax()])