如果列表中只有一个元素,或者要返回列表本身,我的任务是返回列表元素。我使用的方法适用于我的大部分用例,但不适用于字符串。
def inner_value(somelist):
'''
Return somelist[0] if it's a one-element list or the whole list otherwise
:param list somelist: list that might contain only one element
:returns: element of somelist or somelist
>>> inner_value([42])
42
>>> inner_value([42,43])
[42, 43]
>>> inner_value([[42]])
42
>>> inner_value([[42,43]])
[42, 43]
>>> inner_value('spam')
'spam'
>>> inner_value(['spam'])
'spam'
>>> inner_value(['spam','eggs','bacon'])
['spam', 'eggs', 'bacon']
.. warning::
This method does not work for dictionaries (KeyError)
or single character strings (infinite recursion)!
'''
try:
if len(somelist) == 1:
return inner_value(somelist[0])
else:
return somelist
except TypeError:
return somelist
有没有更好的方法来做到这一点
inner_value('spam') == 'spam'
?
答案 0 :(得分:1)
您可以使用isinstance
方法检查变量类型:
if isinstance(somelist, list):
if len(somelist) == 1:
return somelist[0]
else:
return somelist
else:
return somelist
如果你只检查len,它会导致问题,因为len也会给出字符串的大小:
>>> len(['first','second','third'])
3
>>> len('arbitrary')
9