Python中的Sports Seeding函数

eqoofvh9  于 2023-04-28  发布在  Python
关注(0)|答案(2)|浏览(110)

我正在用Python编写一个体育种子程序。我有它的开始在下面。当我运行程序时,我的状态定位器不会在顶部打印出来。谁能给予我一个提示,为什么它不会排序到顶部?

seeded_players = {
2: {'name': 'George', "highschool": "AHS",   "win_rate": 0,  "state": "", "regionals": 6 },
3: {'name': 'George', "highschool": "SCHS",   "win_rate": 0,  "state": "", "regionals": "" },
1: {'name': 'Bob', "highschool": "SHS",   "win_rate": 0.4,  "state": 1, "regionals": 4 },
}

def state_sorting(request):
    # Always sort first in states at the top of list.

    for x in seeded_players:
        if x["State"] == 1:
            x.sort(-1)
    else:
        None

print(seeded_players)

python3 www.example.com {2: {'name': 'George', 'highschool': 'AHS', 'win_rate': 0, 'state': '', 'regionals': 6}, 3: {'name': 'George', 'highschool': 'SCHS', 'win_rate': 0, 'state': '', 'regionals': ''}, 1: {'name': 'Bob', 'highschool': 'SHS', 'win_rate': 0.4, 'state': 1, 'regionals': 4}}

z9gpfhce

z9gpfhce1#

您没有向我们展示执行此代码的单元测试。
我无法想象你如何调用它而不引发异常:

self.id = id
    ...
    if id["State"] == 1:
        id.sort(-1)

给出:

>>> id
<built-in function id>

你想要这样的东西:

from pprint import pp
from collections import namedtuple

Player = namedtuple("Player", "state regionals win_rate name highschool")

seeded_players = [
    Player(1, 4, .4, "Bob", "SHS"),
    Player(0, 6, 0,  "George", "AHS"),
    Player(0, 0, 0,  "George", "SCHS"),
]

那就很简单了

>>> pp(sorted(seeded_players))
[Player(state=0, regionals=0, win_rate=0, name='George', highschool='SCHS'),
 Player(state=0, regionals=6, win_rate=0, name='George', highschool='AHS'),
 Player(state=1, regionals=4, win_rate=0.4, name='Bob', highschool='SHS')]
qgelzfjb

qgelzfjb2#

我认为这反映了你想做的事情。其中的变化:

  • 我已经把你的seeded_players做成了一个列表,而不是一个命令。这是存放需要分类的东西的正确方法。
  • 我把你的state_sorting改成了一个排序键函数。给定一行,它返回一个“键”,告诉该行应该如何排序。在这种情况下,“state”值是最重要的,其次是“regionals”,然后是“win_rate”。
  • 我现在使用这个函数,你没有,通过使用我的函数作为键对列表进行排序。
from pprint import pprint
seeded_players = [
    {'id': 2, 'name': 'George', "highschool": "AHS",   "win_rate": 0,  "state": 0, "regionals": 6 },
    {'id': 3, 'name': 'George', "highschool": "SCHS",   "win_rate": 0,  "state": 0, "regionals": 0 },
    {'id': 1, 'name': 'Bob', "highschool": "SHS",   "win_rate": 0.4,  "state": 1, "regionals": 4 },
]

def state_sorting(row):
    return row['state'],row['regionals'],row['win_rate']

seeded_players.sort( key=state_sorting, reverse=True )
pprint(seeded_players)

输出:

[{'highschool': 'SHS',
  'id': 1,
  'name': 'Bob',
  'regionals': 4,
  'state': 1,
  'win_rate': 0.4},
 {'highschool': 'AHS',
  'id': 2,
  'name': 'George',
  'regionals': 6,
  'state': 0,
  'win_rate': 0},
 {'highschool': 'SCHS',
  'id': 3,
  'name': 'George',
  'regionals': 0,
  'state': 0,
  'win_rate': 0}]

相关问题