【问题标题】:Conditional without the if clause?没有 if 子句的条件?
【发布时间】:2020-12-10 12:55:38
【问题描述】:
def count_emma(statement):
    print("Given String: ", statement)
    count = 0
    for i in range(len(statement) - 1):
        count += statement[i: i + 4] == 'Emma'
    return count

count = count_emma("Emma is good developer. Emma is a writer")
print("Emma appeared ", count, "times")

在这个程序中,我必须找出“Emma”在以下语句中出现的次数:“Emma is good developer. Emma is a writer”。

我的问题:我不明白第 5 行发生了什么。没有 if 子句怎么是条件语句?语句中每次出现“Emma”时,计数如何增加 1?

【问题讨论】:

  • "Emma 是优秀的开发者。Emma 是作家".count("Emma")
  • True 等于1False 等于0,所以如果条件为真,则添加1,如果条件为假,则添加0
  • count += statement[i: i + 4] == 'Emma' 声明正在做这项工作,但我不认为它是 pythonic。
  • @VishalSingh 是的,我真的不知道它是如何完成这项工作的
  • 这不是一个好榜样。 if .... : count += 1 会更清晰,更易于维护(尽管还有其他解决整体问题的方法)。

标签: python function conditional-statements


【解决方案1】:

首先,没有要求条件只能与if 一起使用。即使抛开可以在while 中使用 if 的可能性,您也可以将条件绑定到变量或以其他方式使用它:

>>> x = (1 < 2) ; print(x)
True
>>> print(10 < 4)
False

条件,在需要 整数 的上下文中,将 1 表示真,0 表示假,根据以下记录:

>>> count = 0
>>> count += (7 > 2) ; print(count)
1
>>> count += (7 > 20) ; print(count)
1

因此,对于字符串中的每个起始位置,如果在其中找到Emma,则添加一个,否则为零。

不幸的是,这也会引起对她兄弟 Emmanuel 的任何提及,因此您可能需要考虑到这一点。 一个的方法是确保前后都有空格,并将所有非字母字符替换为空格,然后只需使用string.count() 计算多少次Emma两边都有空格:

>>> import re
>>> x = "Emma is good developer. Emma is a writer. Emmanuel is her brother."
>>> re.sub("[^A-Za-z]+", " ", f" {x} ").count(" Emma ")
2

可能还有很多other方法,我只是更习惯于正则表达式。

【讨论】:

  • 非常感谢您提供清晰准确的解释。 (:
【解决方案2】:

在 python 中有一个自动转换。所以当你把一个整数和一个浮点数相加时,整数会转换成浮点数再进行运算。

例如,print(2 + 2) 只会显示 4,但 print(2+2.0) 会显示 4.0,这是因为整数 2 被转换为浮点数。

当你添加一个整数和一个布尔值时,也会发生同样的事情,布尔值被转换为一个整数。

例如,print(True + 2) 显示 3

但这不仅适用于加法运算,也适用于比较。

例如,同时执行print(2==2.0)print(True == 1) 应该打印True,因为2 先转换为浮点数,然后True 转换为整数。

所以在你的程序中也会发生同样的事情。 首先statement[i: i + 4] == 'Emma' 返回TrueFalse,具体取决于值。然后count += statement[i: i + 4] == 'Emma'(与count = count + statement[i: i + 4] == 'Emma' 等价)将执行布尔值和整数加法。正如我在上面告诉你的,这将导致布尔值被转换为整数并执行操作。

【讨论】:

  • 哇,我现在完全明白了。非常感谢^_^
猜你喜欢
  • 2019-09-14
  • 2022-11-05
  • 2016-06-20
  • 2021-11-30
  • 2017-06-16
  • 2013-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多