【问题标题】:Shorten an if statement whose statement are reversed缩短其语句被反转的 if 语句
【发布时间】:2019-10-11 12:48:31
【问题描述】:

我有以下情况:

string = "abc"
if (string[1] == "b" and string[2] == "c") or (string[1] == "c" and string[2] == "b"):
    print("ERROR")

有没有办法以 Python 的方式缩短它? 我看到(string[1] == "b" and string[2] == "c")(string[1] == "c" and string[2] == "b") 的相反语句。也许我可以使用它?

【问题讨论】:

  • string[1] == "b" and string[2] == "c" 不是string[1] == "c" and string[2] == "b" 的相反语句。这是!(string[1] == "b" and string[2] == "c")string[1] != "b" OR string[2] != "c"
  • 索引是否重要,或者您是否真的想检查string 中是否存在 substr "bc" 或 "cb" ?
  • @Cid 抱歉,我的意思是只交换了“b”和“c”
  • @magnus question 对您的问题很重要
  • @magnus 我想检查字符串中是否存在子字符串“bc”或“cb”。但它们必须是第二个第三个字母

标签: python algorithm if-statement code-readability


【解决方案1】:

有没有办法以pythonic的方式缩短它?

是的,这里是:

string = "abc"
if (string[1:3] == "bc") or (string[1:3] == "cb"):
    print("ERROR")

如果渴望更短的方式 - if string[1:3] in ('bc', 'cb'):

【讨论】:

  • 可能会补充一点,如果模式是任意的并存储在名为pattern="bc" 的变量中,它可能会被pattern[::-1] 反转以获得“cb”
猜你喜欢
  • 1970-01-01
  • 2012-07-05
  • 1970-01-01
  • 1970-01-01
  • 2016-03-26
  • 2018-08-19
  • 1970-01-01
  • 1970-01-01
  • 2017-01-16
相关资源
最近更新 更多