擅长:python、mysql、java
<p>要测试列表中的所有项是否都是字符串,请使用内置的<a href="http://docs.python.org/2/library/functions.html#all" rel="noreferrer">^{<cd1>}</a>和生成器:</p>
<pre><code>if all(isinstance(s, str) for s in lis):
</code></pre>
<p>注意,如果您的列表是空的,那么仍然会返回<code>True</code>,因为从技术上讲,这是一个0字符串的列表。但是,由于您希望将<code>[]</code>视为<code>False</code>,因此需要执行以下操作:</p>
<pre><code>if lis and all(isinstance(s, str) for s in lis):
</code></pre>
<p>所以,你的功能应该是这样的:</p>
<pre><code>def checktype(obj):
# This if statement makes sure input is a list that is not empty
if obj and isinstance(obj, list):
return all(isinstance(s, str) for s in obj)
else:
return False
</code></pre>
<p>如果该函数的输入是一个不为空且完全由字符串组成的列表,则它只返回<code>True</code>。其他任何东西(如<code>[]</code>、<code>['a', 1]</code>、<code>('a', 'b')</code>等)都会使它返回<code>False</code>。</p>
<p>另外,以这种方式使用<code>all</code>还有一个额外的好处,因为它停止检查它找到的第一个返回<code>False</code>(不是字符串)的项。这使您能够非常高效地处理非常大的列表。</p>