我怎么能重写这一行?

时间:2014-10-14 12:13:17

标签: python pygame

在我的代码中,我有以下一行:

something = next((s for s in something if s.rect.collidepoint(pygame.mouse.get_pos())), None)  

我的问题是,如何将这句话重写几行,这样会使我的代码更清晰?

3 个答案:

答案 0 :(得分:2)

def next_something(something):
    for s in something:
        if s.rect.collidepoint(pygame.mouse.get_pos()):
            return s
    return None

something = next_something(something)

答案 1 :(得分:1)

您可以从更具描述性的命名变量开始,也许使用中间变量。

即使我也这样做,当右侧的变量与左侧的变量同名时,我发现它不可读。

filtered_something = (s 
                      for s in something
                      if s.rect.collidepoint(pygame.mouse.get_post())
first_something = next(filtered_something, None)

答案 2 :(得分:-1)

这是pep8兼容的

something = next((
    s for s in somethin
    if s.rect.collidepoint(pygame.mouse.get_pos())),
    None)