![](/img/trans.png)
[英]Can I call a Python function without brackets, like a shell command. If so, how?
[英]how can i delet brackets with this command?
我想用这种代码或递归 function 从这个列表中删除括号,首先请让我知道这些代码有什么问题,然后请给我正确的代码谢谢
def fun(a) :
x = []
while a[0,len(a)+1] is not int :
for i in range(len(a)):
b = a[i]
b = b[0] if b is not int else b
if b is int :
x.append(b)
break
return x
l = [[1],[2],[[3]],[[[4]]]]
print(fun(l))
或者
L = [[[[1]]], [[2, 3, 4, 5]], [6, 7, 8], [9, 10]]
x = []
b = []
for i in range(len(L)):
while L[i] is not int:
if b is int:
L[i].append(x)
break
else:
b = L[i]
b = b[0]
L[i] = b
print(L)
希望这可以帮助:
L = [[[[1]]], [[2, 3, 4, 5]], [6, 7, 8], [9, 10]]
def remove_brackets(L):
L_cleaned = []
for i in L:
j = i
while type(j[0]) is not int:
j = j[0]
for k in j:
L_cleaned.append(k)
return L_cleaned
remove_brackets(L)
要处理由多个嵌套列表组成的列表(例如[[[1, 2], [3, 4]]]
),您需要这样的东西:
def check(l):
# check if all extra brackets removed
for x in l:
if not type(x) is int:
return False
return True
def fun(l):
new_l = []
for x in l:
if type(x) is int:
new_l.append(x)
else:
# x is list
new_l.extend(fun(x))
return new_l
或者:
def bar(l):
return str(l).replace("[", "").replace("]", "").split(",")
而不是使用type(x) is...
你通常应该使用isinstance
。 这是一个简单的递归解包 function。
def unpack(item):
if isinstance(item, list):
for subitem in item:
yield from unpack(subitem)
else:
yield item
L = [[[[1]]], [[2, 3, 4, 5]], [6, 7, 8], [9, 10]]
L2 = list(unpack(L)) # L2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.