2021年3月11日星期四

remove multiple layers of lists in a list

I want to make a function that removes any layers of lists in a list

Example

[[[[1,2]]],[[3,4]]] --> [(1,2),(3,4)]

[(1, 2), [(1, 2)]] -->[(1,2),(1,2)]

Here is my attempt using recursion which didnt work on the second example.

def nolistlist(t):       flat_list = []      for i in t:          if isinstance(i,list):              for x in t:                     if type(x) == list:                      for y in x:                          flat_list.append(y)                  else:                      flat_list.append(x)              return nolistlist(flat_list)          else:              return t   

Anyone that has a simple solution without importing any library? I know the problem but cant come up with a solution. Have been trying to solve this problem for while now. Help would be appreciated!

https://stackoverflow.com/questions/66592778/remove-multiple-layers-of-lists-in-a-list March 12, 2021 at 09:08AM

没有评论:

发表评论