Python 递归删除所有空格(列表的列表的列表…)
我正在尝试从输入中删除所有空格,即列表列表列表。。。我不知道该为“其他”做些什么: 例如:Python 递归删除所有空格(列表的列表的列表…),python,recursion,space,Python,Recursion,Space,我正在尝试从输入中删除所有空格,即列表列表列表。。。我不知道该为“其他”做些什么: 例如: a = [" foo", [" spam", "ham"], " bar"] print rreplace(a, " ", "") 输出应为: lst2 = [apple,pie,[sth,[banana,asd,[sdfdsf,[fgg]]]]] 如果lst包含整数或浮点,该怎么办?我收到了整数的错误 输入示例: L = [['apple', '2 * core+1* sth'
a = [" foo", [" spam", "ham"], " bar"]
print rreplace(a, " ", "")
输出应为:
lst2 = [apple,pie,[sth,[banana,asd,[sdfdsf,[fgg]]]]]
如果lst包含整数或浮点,该怎么办?我收到了整数的错误
输入示例:
L = [['apple', '2 * core+1* sth'], ['pie', '1*apple+1*sugar+1*water'], ['water', 60]]
印刷品
['apple', 'pie', ['sth', ['banana', 'asd', ['sdfdsf', ['fgg']]]]]
我建议遵循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)
以下是一个示例:
>>> removespace([["a ",[" "]],{"b ","c d"},"e f g"])
[['a', ['']], {'b', 'cd'}, 'efg']
虽然您可以尝试使用递归解决方案,但您可以尝试使用Python提供的出色库,将格式良好的Python文本从字符串转换为Python文本
- 只需将列表转换为字符串
- 删除所有必要的空间
- 然后使用
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)
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']
>>> lst = [' apple', 'pie ', ['sth', ['banana', 'asd', [' sdfdsf', ['fgg']]]]]
>>> import ast
>>> ast.literal_eval(str(lst).translate(None,' '))
['apple', 'pie', ['sth', ['banana', 'asd', ['sdfdsf', ['fgg']]]]]