Python中检查字符序数的不等式

33 <= cp <= 47写类似vs的东西有区别cp >= 33 and cp <= 47吗?


更具体地说,如果有一个函数可以:


def _is_punctuation(char):

  """Checks whether `chars` is a punctuation character."""

  cp = ord(char)

  if ((cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or

      (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126)):

    return True

  else:

    return False

是否与以下内容相同:


def is_punctuation(char):

    """Checks whether `chars` is a punctuation character."""

    # Treat all non-letter/number ASCII as punctuation.

    # Characters such as "^", "$", and "`" are not in the Unicode

    # punctuation class but treat them as punctuation anyways, for consistency.

    cp = ord(char)

    if (33 <= cp <= 47) or (58 <= cp <= 64) or (91 <= cp <= 96) or (123 <= cp <= 126):

        return True

    return False

是否有理由更喜欢_is_punctuation()或is_punctuation()反之亦然?


一个在计算上会比另一个更快吗?如果是这样,我们如何验证呢?使用dis.dis?


收到一只叮咚
浏览 103回答 1
1回答

哔哔one

不,它们在语义上是相同的。您也可以返回条件而不是使用 if 子句,因为它无论如何都会评估为布尔值:return&nbsp;(33&nbsp;<=&nbsp;cp&nbsp;<=&nbsp;47)&nbsp;or&nbsp;(58&nbsp;<=&nbsp;cp&nbsp;<=&nbsp;64)&nbsp;or&nbsp;(91&nbsp;<=&nbsp;cp&nbsp;<=&nbsp;96)&nbsp;or&nbsp;(123&nbsp;<=&nbsp;cp&nbsp;<=&nbsp;126)他们(谷歌 AI 工程师)可能不知道链式比较,或者他们希望它表现得更好一些。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python