【发布时间】:2018-05-12 15:14:49
【问题描述】:
1) 在列表推导中使用多个条件 if 语句的最 Pythonic 方式是什么?
2) Len() 在调用函数时如果串接了字符串会返回错误。
Len(str(x) + str(y)) is not allowed
第 2 点不正确,留给未来的读者
在使用 if len() 语句时使用 lambda 是否合适,如下所示: ?
for j in blah:
for i in range(4):
inputs = set([ str(j) + "".join(x) for x in itertools.permutations(total, i) if 14 > len(lambda j,x : str(j) + "".join(x)) and len(lambda j, x : str(j) + "".join(x)) > 9])
【问题讨论】:
-
如果我必须维护
inputs = set([ str(j) + "".join(x) for x in itertools.permutations(total, i) if 14 > len(lambda j,x : str(j) + "".join(x)) and len(lambda j, x : str(j) + "".join(x)) > 9]),我会诅咒你的。这不是 Pythonic。 -
它是
len而不是Len。你的第二点是不正确的。len('a' + 'b') == 2 -
您正在使用 lambda 的
len,这是一个函数。这没有意义,而且会失败。 -
你可以链接你的比较器来获得
9 < len(lambda j, x: str(j) + "".join(x)) < 14它有助于可读性,有点 -
在 SO 上有些东西创建 1-liners 很有吸引力,但不应该以牺牲可读性为代价。请记住,您所写的内容在长度方面也违反了 PEP8,因此必须将其分成几行。这实际上可能有助于提高可读性。
标签: python lambda syntax list-comprehension