我正在尝试从列表列表列表的输入中删除所有空格...我不知道该怎么做“else:”
def removespace(lst):
if type(lst) is str:
return lst.replace(" ","")
else:
?????
示例:的
lst = [ apple, pie , [sth, [banana , asd, [ sdfdsf, [fgg]]]]]
输出应为:
lst2 = [apple,pie,[sth,[banana,asd,[sdfdsf,[fgg]]]]]
如果lst包含整数或浮点,该怎么办?我收到整数错误。
示例输入:
L = [['apple', '2 * core+1* sth'], ['pie', '1*apple+1*sugar+1*water'], ['water', 60]]
答案 0 :(得分:4)
def removespace(a):
if type(a) is str:
return a.replace(" ", "")
elif type(a) is list:
return [removespace(x) for x in a]
elif type(a) is set:
return {removespace(x) for x in a}
else:
return a
以下是一个示例:
>>> removespace([["a ",[" "]],{"b ","c d"},"e f g"])
[['a', ['']], {'b', 'cd'}, 'efg']
答案 1 :(得分:2)
我建议关注EAFP并捕获异常,而不是使用isinstance
。此外,永远不要错过让函数更通用的机会:
def rreplace(it, old, new):
try:
return it.replace(old, new)
except AttributeError:
return [rreplace(x, old, new) for x in it]
示例:
a = [" foo", [" spam", "ham"], " bar"]
print rreplace(a, " ", "")
或者甚至更通用,虽然这可能对你的问题有点过分:
def rapply(it, fun, *args, **kwargs):
try:
return fun(it, *args, **kwargs)
except TypeError:
return [rapply(x, fun, *args, **kwargs) for x in it]
a = [" foo", [" spam", "ham"], " bar"]
print rapply(a, str.replace, " ", "")
print rapply(a, str.upper)
答案 2 :(得分:0)
def removespace(lst):
if type(lst) is str:
return lst.replace(" ","")
else:
return [removespace(elem) for elem in lst]
lst = [' apple', 'pie ', ['sth', ['banana', 'asd', [' sdfdsf', ['fgg']]]]]
print removespace(lst)
打印
['apple', 'pie', ['sth', ['banana', 'asd', ['sdfdsf', ['fgg']]]]]
答案 3 :(得分:0)
虽然您可以尝试使用递归解决方案,但是您可以尝试使用Python提供的精彩库,将格式良好的Python文字从字符串转换为Python文字。
然后使用ast.literal_eval
重新转换为递归列表结构>>> lst = [' apple', 'pie ', ['sth', ['banana', 'asd', [' sdfdsf', ['fgg']]]]]
>>> import ast
>>> ast.literal_eval(str(lst).translate(None,' '))
['apple', 'pie', ['sth', ['banana', 'asd', ['sdfdsf', ['fgg']]]]]