【问题标题】:Most pythonic way to use len() based conditions with multiple arguments in a list comprehension在列表理解中使用具有多个参数的基于 len() 的条件的大多数 Pythonic 方式
【发布时间】: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


【解决方案1】:

您的代码不起作用,并且您没有用于验证的示例输入和输出,所以我在这里猜测一下。我多次看到str(j) + "".join(x),这是生成器顺序错误的一个很好的指标。你正在做str(j) 很多,这暗示一些预处理是有序的。它还有助于以明确变量的方式命名变量。并且添加间距以保持行短并按逻辑分组使以后更容易扫描。

import itertools

blah = [10**n for n in range(5,15)]
total = 'fubar'

for blahval, permlen in itertools.product(map(str,blah), range(4)):
    inputs = set((newinput for newinput in
        (blahval + "".join(permutation)
            for permutation in itertools.permutations(total, permlen))
        if 14 > len(newinput) > 9))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-26
    • 1970-01-01
    • 1970-01-01
    • 2015-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多