0

player = [一长串(id,float)元组,每个id都是唯一的,按最高float排序]

on_teams = [唯一ID列表,每个on_teams id也在球员列表中]

picked = set(on_teams)
best_remaining = []
for best_player in players:
    if best_player[0] not in picked:
        best_remaining.append(best_player)
    if len(best_remaining) == 5: break

当我用六行代码来做一件简单的事情,比如“获得剩下的五个最好的玩家”时,我想知道是否没有更优雅、pythonic 的解决方案。毫无疑问,这是一个简单的问题,但有更好的编码方法吗?

更新:我的代码运行 100,000 次,运行时间为 0.24 秒。当我运行时:

best_remaining = [(id, float) for id, float in players if id not in picked][:5]

代码运行时间为 4.61 秒(100,000 倍)。所以代码看起来和扫描得更好,但它会创建整个列表然后对其进行切片。所以现在我的问题有点不同。以速度为限制条件,是否有更好的方法来编码搜索“剩余 5 名最佳球员”?

更新:

best_remaining = list(islice((p for p in players if p[0] not in picked), 5))

这段代码的运行时间比我的代码要长得多。至少对我来说,它具有列表理解的价值。最重要的是,它向我展示了一个改善我的代码习惯的好地方。谢谢

4

2 回答 2

3

使用生成器,然后islice最多生成 5 个结果...

from itertools import islice
picked = set(on_teams)
players = list(islice((p for p in players if p[0] not in picked), 5))
于 2013-02-25T16:28:17.023 回答
0

numpy 非常适合这样的事情

players = numpy.array([[1,1.1],[2,1.2],[3,3.2],[4,4.4]])
on_teams = [1,3]
print players[~numpy.in1d(players[:,0],on_teams)]  #all players not on teams (in example 2,4)
# now you can just select the top n players
于 2013-02-25T16:28:06.377 回答