【问题标题】:if variable == 'String' : doSomething()? [duplicate]如果变量 == 'String' : doSomething()? [复制]
【发布时间】:2018-10-24 03:44:18
【问题描述】:

我将 if 语句控制流中列表 ['a','c'] 的每个元素与如下字符串进行比较:

charlist = ['a','b']

for el in charlist:
    if el is'a' or 'A':
        print('a is done')
    if el is 'b' or 'B':
        print('b is done')
    if el is 'c' or 'C':
        print('why c?')

输出是:
完成了
b 完成了
为什么是c?

为什么会执行“if el is 'c' or 'C':”语句?
我认为只有前两个被执行?

但这个解决方案对我有用

for el in charlist:
    if el == 'a' or el == 'A':
       print('a is done')
    if el == 'b' or el == 'B':
       print('b is done')
    if el == 'c' or el == 'C':
       print('c is done')

【问题讨论】:

  • el is 'c' or 'C': -> el == 'c' or el=='C'
  • @EliKorvigo 他们是 ifs,而不是 elifs。
  • 它对我有用@mad_,谢谢
  • @dfundako 确实如此,我已经删除了我的评论。我的视觉皮层中的模式匹配器将if el 误认为elif
  • 您也可以看看这个post,因为它与您的问题完全相同,而且 cmets 显示的解决方案比您选择的解决方案更好。

标签: python dictionary if-statement


【解决方案1】:

为了清楚起见,尝试这样做:

charlist = ['a','b']

for el in charlist:
  if el =='a' or el =='A':
     print('a is done')
  if el == 'b' or el =='B':
     print('b is done')
  if el == 'c' or el == 'C':
      print('why c?')

【讨论】:

    猜你喜欢
    • 2019-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-01
    • 2012-11-03
    • 1970-01-01
    • 2011-09-11
    • 2011-01-12
    相关资源
    最近更新 更多