【问题标题】:Why IF condition does not work with "OR" in python为什么IF条件不适用于python中的“OR”
【发布时间】:2021-04-19 08:14:44
【问题描述】:

问题是,OR 不适用于 python 3 中的 IF 条件,如果我编写多个 IF 条件,那么它可以正常工作,如下所示:

s1 has 3 matches in text[i]
s2 has 1 matches in text[i]
text[i] is read line by line and contain s1 OR s1 

不工作:

c=0
if s1 in text[i] or s2 in text[i]:
  c = c + 1 

输出:

3    # here correct total 4 condition, s1 true as 3 and s2 true as 1 !

工作:

c=0
if s1 in text[i] :
   c = c + 1 
if s2 in text[i] :
   c = c + 1 

期望/正确结果为 4

如何将两个条件写在一行中?

【问题讨论】:

  • 第一个代码将 c 保留为 0 或 1。第二个代码将 c 保留为 0、1 或 2。它们都没有将其设置为 4。它们都没有输出任何内容。跨度>
  • @khelwood 我更新了问题,如果有任何疑问,请告诉我
  • 您似乎正在寻找多个匹配项。您不能为此使用in,因为in 停止查看第一场比赛。查找字符串方法count() 并改用它。
  • 也许您想发布一个 minimal reproducible example 来实际展示您所描述的行为。
  • 考虑如果s1s2 都在text[i] 中会发生什么。

标签: python python-3.x if-statement syntax


【解决方案1】:

因为你没有迭代你可以从 if 中得到的每一个真理。

下面的代码会给你你想要的。

s1 = "f"
s2 = "b"
text = "foo foo buzz"


def check_if_in_str(x, I):
    return x in text[i]


variables = [s1, s2]
c = 0
for i in text:
    for variable in variables:
        if check_if_in_str(variable, I):
            c += 1

请记住,这不是发明轮子的最佳实践,您应该使用 set 函数 count() 有关更多信息,请参阅此参考: https://www.programiz.com/python-programming/methods/string/count

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-06
    • 1970-01-01
    • 1970-01-01
    • 2016-12-06
    • 1970-01-01
    • 2021-03-31
    • 1970-01-01
    相关资源
    最近更新 更多