擅长:python、mysql、java
<p>使用内置的<code>all()</code>函数。</p>
<pre><code>if bag and all(elem == "drink" for elem in bag):
print("Only 'drink' is in the bag")
</code></pre>
<p><code>all()</code>函数如下:</p>
<pre><code>def all(iterable):
for element in iterable:
if not element:
return False
return True
</code></pre>
<p>因此,空列表将返回True。由于没有元素,它将完全跳过循环并返回True。因为是这种情况,您必须添加一个显式的<code>and len(bag)</code>或<code>and bag</code>,以确保包不是空的(<code>()</code>和<code>[]</code>是假的)。</p>
<p>此外,还可以使用<code>set</code>。</p>
<pre><code>if set(bag) == {['drink']}:
print("Only 'drink' is in the bag")
</code></pre>
<p>或者,类似地:</p>
<pre><code>if len(set(bag)) == 1 and 'drink' in bag:
print("Only 'drink' is in the bag")
</code></pre>
<p>所有这些都将使用列表中的0个或多个元素。</p>