繁体   English   中英

如何使列表推导更具可读性?

[英]How to make list comprehensions more readable?

我在下面有这段代码,如果您是 python 的新手,我认为这有点难以理解。

我将如何 go 使其对 python 的一组新手(学生)更具可读性

def right_inwrongplace(userGuess, number):
    correct_places = [True if v == number[i] else False for i, v in enumerate(userGuess)]
    g = [v for  i, v in enumerate(userGuess) if not correct_places[i]]
    n = [v for  i, v in enumerate(number) if not correct_places[i]]
    return len([i for i in g if i in n])

以下是一些改进:

  • True if x else False只是bool(x)或者,正如您已经在进行比较,只是那个表达式,即v == number[i]
  • 由于您通过位置索引访问数字,因此您只需zip两个序列即可。

所以首先你会得到:

correct_places = [x == y for x, y in zip(userGuess, number)]

zip相同的论点适用于以下两种理解(您可以再次遍历原始字符串):

g = [x for x, y in zip(userGuess, number) if x != y]
n = [y for x, y in zip(userGuess, number) if x != y]

鉴于这两次基本上是相同的理解,并且我们不再需要correct_places ,我们可以改为执行以下操作:

g, n = zip(*[(x, y) for x, y in zip(userGuess, number) if x != y])

然后你可以sum而不是len

return sum(x in n for x in g)

所以基本上你可以使用下面的代码:

g, n  = zip(*(xy for xy in zip(userGuess, num) if xy[0] != xy[1])
return sum(x in n for x in g)

暂无
暂无

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

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