擅长:python、mysql、java
<p>到目前为止,我读到的答案在给出一个非字符串的非列表时会引起注释……而且也是不可编辑的。这个问题在:</p>
<p><a href="https://stackoverflow.com/questions/1952464/in-python-how-do-i-determine-if-an-object-is-iterable">In Python, how do I determine if an object is iterable?</a></p>
<p>采用duck输入法:</p>
<pre><code>def categorize(x):
result = "not a string or list of strings"
if isinstance(x, basestring):
return "It's a single string"
try:
if all(isinstance(y, basestring) for y in x):
return "It's a list of strings"
except TypeError:
pass
return "It's not a list of strings or a single string"
data = [ 5, "xyzzy", list("xyzzy"), ['1', '23', 456]]
for x in data:
print x, categorize(x)
</code></pre>
<p>输出:</p>
<pre><code>5 It's not a list of strings or a single string
xyzzy It's a single string
['x', 'y', 'z', 'z', 'y'] It's a list of strings
['1', '23', 456] It's not a list of strings or a single string
</code></pre>