【问题标题】:How should I obtain an appropriate boolean result?我应该如何获得适当的布尔结果?
【发布时间】:2019-08-22 17:12:19
【问题描述】:

我已经写了一些代码,这里有一小段代码

x = ['apple, iphone','samsung, galaxy','oneplus, 10pro']
print('apple' in x) 

我如何让这个陈述为真,因为苹果已经存在于 x 中,我仍然不断将 False 作为布尔值。

【问题讨论】:

  • 'apple' 不在x 中,'apple, iphone' 在。

标签: python-3.x list list-comprehension


【解决方案1】:

in 运算符应用于您在此处的列表时,它会在列表中查找完全匹配。您的代码返回 false,因为 'apple' 不在列表中,'apple, iphone' 在。要检查列表中每个元素的子字符串'apple',您可以使用列表推导。比如:

x = ['apple, iphone','samsung, galaxy','oneplus, 10pro']
print(True in ['apple' in s for s in x]) 

第二行的作用是使用列表推导构建一个布尔值列表,指示子字符串 'apple' 是否在该元素中。然后它检查True 是否在结果列表中。

或者不使用in 运算符:

x = ['apple, iphone','samsung, galaxy','oneplus, 10pro']
print(any(['apple' in s for s in x])) 

如果可迭代对象中的任何元素是True,则any 内置函数返回true。

【讨论】:

    【解决方案2】:
    x = ['apple, iphone','samsung, galaxy','oneplus, 10pro']
    print(True in ('apple' in d for d in x))
    

    【讨论】:

      【解决方案3】:

      也许使用这样的函数:

      IsItemInList(item, list):
           for x in list:
                if x == item:
                      return True
            return False
      

      很确定有一种更清洁的方法可以做到这一点,但这是我的第一个猜测。正如我们所知,第一个通常是最糟糕的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多