简体   繁体   English

python:选择一个具有列表长度限制的子列表

[英]python: select a sublist with a list length limit

players = [ a long list of (id, float) tuples with each id unique, order by highest float] 玩家= [一长串(id,float)元组,每个id都是唯一的,按最高float排序]

on_teams = [ a list of unique ids, every on_teams id is also in the players list] 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

When I use six lines of code to do a simple thing, such as "get the five best remaining players", I wonder if there isn't a more elegant, pythonic solution. 当我使用六行代码来完成一件简单的事情,例如“获得剩下的五个最好的玩家”时,我想知道是否还没有一个更优雅的Python解决方案。 It's a simple problem, no doubt, but is there a better way to code it? 毫无疑问,这是一个简单的问题,但是有更好的编码方法吗?

UPDATE: My code run 100,000 times, runs in 0.24 secs. 更新:我的代码运行100,000次,运行0.24秒。 When I run: 当我跑步时:

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

The code runs in 4.61 secs (100,000x). 代码运行时间为4.61秒(100,000x)。 So the code looks and scans nicer, but it create the whole list then slices it. 因此,代码看起来和扫描起来更好,但是它创建了整个列表,然后对其进行了切片。 So now my question is a little different. 所以现在我的问题有点不同了。 With speed as a constraint, is there a better way to code up the search for the '5 best remaining players`? 以速度为约束,是否有更好的方法来编码搜索“剩下的5个最佳球员”?

UPDATE: 更新:

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

This code runs trivially longer than my code. 此代码的运行时间比我的代码短。 To me at least, it has the value of a list comprehension. 至少对我来说,它具有列表理解的价值。 And best of all, it shows me a good place to work on my code habits. 最重要的是,它向我展示了我的代码习惯的好地方。 Thanks 谢谢

Use a generator, and then islice it to a max of 5 results... 使用生成器,然后isliceislice为最多5个结果...

from itertools import islice
picked = set(on_teams)
players = list(islice((p for p in players if p[0] not in picked), 5))

numpy is great for something like this 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM