【问题标题】:How to check if a list ONLY contains a certain item如何检查列表是否仅包含某个项目
【发布时间】:2016-03-24 15:27:19
【问题描述】:

我有一个名为 bag 的列表。我希望能够检查其中是否只有特定项目。

bag = ["drink"]
if only "drink" in bag:
    print 'There is only a drink in the bag'
else:
    print 'There is something else other than a drink in the bag'

当然,我在代码中放“only”的地方是错误的。有没有简单的替代品?我试过几个类似的词。

【问题讨论】:

  • if len(bag) == 1 and item in bag:
  • 对不起,我在这里不清楚,但是您的意思是该列表只有一项并且它是“drink”,还是只有“drink”在列表中?换句话说,["drink", "candy bar"] 会通过你的 if only 测试吗?
  • 你不会尝试“几个相似的词”来用编程语言做某事,但你要做的是先学习语言的基础知识,然后用你的知识做事。这是学习的自然过程。
  • @Sнаđошƒаӽ monte-carlo 搜索关键字,做你想做的事,这不是你编程的方式?你错过了
  • 可能重复。 stackoverflow.com/questions/405516/if-all-in-list-something 和Shadowfax 只是个玩笑(随机猜词,直到有效果)

标签: python list


【解决方案1】:

使用内置的all() 函数。

if bag and all(elem == "drink" for elem in bag):
    print("Only 'drink' is in the bag")

all()函数如下:

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True

因此,空列表将返回 True。由于没有元素,它将完全跳过循环并返回 True。因为是这种情况,所以必须添加显式的and len(bag)and bag 以确保包不为空(()[] 类似假)。

另外,您可以使用set

if set(bag) == {['drink']}:
    print("Only 'drink' is in the bag")

或者,类似地:

if len(set(bag)) == 1 and 'drink' in bag:
    print("Only 'drink' is in the bag")

所有这些都适用于列表中的 0 个或更多元素。

【讨论】:

  • 如果包里有其他东西,第一个是唯一短路的(所有好答案)
  • @en_Knight 是的。
  • @en_Knight 不错。我用any!= 替换了它,它们不会在空列表上失败:)
  • 如果不是你需要使用的任何一个,因为如果任何元素不等于drink,那么你拥有的那个是真的
  • 看起来不错 +1。我会切换它,所以 and 语句是第一个(再次短路)但并不重要
【解决方案2】:

您可以直接使用仅包含此项的列表检查是否相等:

if bag == ["drink"]:
    print 'There is only a drink in the bag'
else:
    print 'There is something else other than a drink in the bag'

或者,如果您想检查列表是否包含任何大于零的相同项目"drink",您可以计算它们并与列表长度进行比较:

if bag.count("drink") == len(bag) > 0:
    print 'There are only drinks in the bag'
else:
    print 'There is something else other than a drink in the bag'

【讨论】:

  • Sam 的问题是 Lafada 的问题 - ["drink","drink"] 怎么样?那不就是只喝饮料吗?
  • 不确定。问题中没有明确描述。但我也为此添加了一个替代方案。
  • 好的,第二个似乎几乎正确。只是为了迂腐,它在空列表上失败了
  • ["drink","drink"] 确实符合只喝饮料的条件。我只是意识到我的问题并不清楚。第二个效果最好
  • 第二个最适合测试是否没有别的东西,但正如@ByteCommander 间接指出的那样,[].count("drink") == len([]) 确实评估为 True。
【解决方案3】:

您可以检查列表的长度

if len(bag) == 1 and "drink" in bag:
    #do your operation.

【讨论】:

  • 似乎 ['drink','drink'] 应该有资格在其中只喝饮料,但在您的实施中没有
  • 是的,你是对的 :),然后必须检查 all 第二个答案 :)
猜你喜欢
  • 2012-08-26
  • 1970-01-01
  • 2011-08-17
  • 2021-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-18
相关资源
最近更新 更多