【问题标题】:If for loops doesn't yield anything, how to generate an certain output message如果 for 循环不产生任何结果,如何生成某个输出消息
【发布时间】:2021-04-17 09:40:51
【问题描述】:
a = ['apple', 'banana', 'guava', 'pineapple']
x = 5

for i in range (len(a)):
    if len(a[i]) == x:
        print(a[i])

如果 x 为 5,则输出为:

apple
guava

否则,如果我将 x 更改为 3,则根本没有输出。 如果只有在 for 循环中没有满足条件的元素,如何生成类似“没有具有预期长度的元素”的消息。

所以,当它变成这样时

a = ['apple', 'banana', 'guava', 'pineapple']
    x = 3

for i in range (len(a)):
    if len(a[i]) == x:
        print(a[i])

由于在for循环中没有满足条件的元素,所以预期的输出是:

There is no element with the expected lengths

【问题讨论】:

    标签: python arrays for-loop


    【解决方案1】:

    您可以为此使用额外的变量。

    a = ['apple', 'banana', 'guava', 'pineapple']
    x = 3
    found=False
    for i in range (len(a)):
        if len(a[i]) == x:
            print(a[i])
            found=True
    if found==False:
        print('There is no element with the expected lengths')
    

    【讨论】:

      【解决方案2】:

      使用第三方变量来跟踪循环中发生的事情

      a, x = ['apple', 'banana', 'guava', 'pineapple'], 3
      at_least_one = False
      for word in a:
          if len(a) == x:
              print(a)
              at_least_one = True
      if not at_least_one:
          print('There is no element with the expected lengths')
      

      使用列表理解和布尔技巧

      a, x = ['apple', 'banana', 'guava', 'pineapple'], 3
      matchings = [w for w in a if len(w) == x] or ['There is no element with the expected lengths']
      print("\n".join(matchings))
      
      • 列表[w for w in a if len(w) == x] 得到所有正确的单词

      • 如果为空,则为 Falthy,使用 or 运算符,它将返回另一个操作数,即文本

      • 然后打印你得到的任何东西

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-09-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-06
        • 1970-01-01
        • 2020-01-11
        相关资源
        最近更新 更多