I want to delete brackets from this list with this kind of code or with a recursive function first of all please let me know what's wrong whit these codes and then please give me the correct code thanks
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))
or
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)
CodePudding user response:
hope this helps:
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)
CodePudding user response:
To deal with lists that consist of multiple nested-lists (e.g. [[[1, 2], [3, 4]]]
), you'll need something like this:
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
alternatively:
def bar(l):
return str(l).replace("[", "").replace("]", "").split(",")
CodePudding user response:
Instead of using type(x) is ...
you should generally use isinstance
. Here is a simple, recursive unpack 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]