ljsq.net
当前位置:首页 >> 如何把嵌套的python list转成一个一维的python list >>

如何把嵌套的python list转成一个一维的python list

def flattern(nested): result = [] if isinstance(nested, list): for sublist in nested: result.extend(flattern(sublist)) else: result.append(nested) return resulta = [[1,2],3,5,[[6,7],[8]]]flattern(a) # [1,2,3,5,6,7,8]

def expand(item): if isinstance(item, list): for sub in item: for i in expand(sub): yield i else: yield item list(expand(?))

在确定list里的所有元素都是字符串的前提下,用字符串中的join()函数就可以实现: str = "".join(lst) #""即空字符串

不知道你想怎么处理那个嵌套的list? l = [1,2,[3,4,5],'6','a',['b','c',7]] newList = [] for item in l: if type(item) == list: tmp = '' for i in item: tmp +=str(i)+ ' ' newList.append(tmp) else: newList.append(item) print(newList) ...

不知道你想怎么处理那个嵌套的list? l = [1,2,[3,4,5],'6','a',['b','c',7]]newList = []for item in l:if type(item) == list:tmp = ''for i in item:tmp +=str(i)+ ' 'newList.append(tmp)else:newList.append(item)print(newList)# [1, 2, '3...

# coding=utf-8# using python2.7(python3没有这个函数)from compiler.ast import flattenyour_list = [[[1, 2, 3], [4, 5]], [[1, 2, 3], [4, 5, 6,7,8]]]print flatten(your_list) # [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6, 7, 8]

在确定list里的所有元素都是字符串的前提下,用字符串中的join()函数就可以实现: str = "".join(lst) #""即空字符串

def translist(l): result=[] for element in l: if type(element)==type([]): result.extend(translist(element)) else: result.append(element) return result

python2的话 >>> from compiler.ast import flatten >>> flatten(a) reduce(lambda x,y:x+y, a)

my_list = list() def to_list(lt): for item in lt: if isinstance(item, list): to_list(item) else: my_list.append(item) if __name__ == '__main__': a = [[1,2,3], [4,5,6]] my_list = list() to_list(a) print my_list

网站首页 | 网站地图
All rights reserved Powered by www.ljsq.net
copyright ©right 2010-2021。
内容来自网络,如有侵犯请联系客服。zhit325@qq.com