擅长:python、mysql、java
<p>因为您有多种类型的数据,所以您可能希望使用递归函数获取单个项的类型,如下所示</p>
<pre><code>def get_type(data):
if isinstance(data, list):
types = {get_type(item) for item in data}
# If all elements of the list are of the same type
if len(types) == 1:
return next(iter(types))
# if not, return "multiple"
else:
return "multiple"
elif isinstance(data, str):
# Check if the string has only numbers or it is a float number
return "numeric" if data.isdigit() or is_float(data) else "character"
elif isinstance(data, int) or isinstance(data, float):
return "numeric"
</code></pre>
<p>助手函数<code>is_float</code>的定义如下</p>
<pre><code>def is_float(data):
try:
float(data)
return True
except ValueError:
return False
</code></pre>
<p>还有测试</p>
<pre><code>assert(get_type(["hello", "world"]) == "character")
assert(get_type("hello") == "character")
assert(get_type(['1.0', '0.0']) == "numeric")
assert(get_type([0, 1, 2]) == "numeric")
assert(get_type(0.100) == "numeric")
</code></pre>