Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 扁平列表_Python_List_Dictionary_Tuples_Flatten - Fatal编程技术网

Python 扁平列表

Python 扁平列表,python,list,dictionary,tuples,flatten,Python,List,Dictionary,Tuples,Flatten,我希望得到一个包含多个嵌套列表的列表: 列表1=[[1,2],[3[4,5]],6[7]] 输出-->[1,2,3,4,5,6,7] 我刚刚加入了Stack overflow,因此无法发布类似趋势问题的答案 因此,我在这里发布我的答案,我认为这是最快的,如果有人得到更好的解决方案,请告诉我。同时,人们可以参考以下内容进行处置: a = str(list1) #Convert list to String a = a.replace('[','') a = a.replace(']','') #

我希望得到一个包含多个嵌套列表的列表:

列表1=[[1,2],[3[4,5]],6[7]] 输出-->[1,2,3,4,5,6,7]

我刚刚加入了Stack overflow,因此无法发布类似趋势问题的答案

因此,我在这里发布我的答案,我认为这是最快的,如果有人得到更好的解决方案,请告诉我。同时,人们可以参考以下内容进行处置:

a = str(list1)  #Convert list to String
a = a.replace('[','')
a = a.replace(']','') # remove '['&']' from the list use specific brackets for other data structures
# in case of dictionary replace ':' with ','
b=a.split(',')  # Split the string at ','
d = [int(x) for x in b]
这应该能够为任何级别的复杂列表实现

Dnyanraj Nimbalkar aka Samrat试试这个:

list_ = [[1,2],[3,[4,5]],6,[7]]

def flatten_list(input_, output):
    for item in input_:
        if isinstance(item, list):
            flatten_list(input_ = item, output = output)
        else:
            output.append(item)
    return output

output = flatten_list(input_ = list_, output = list())
print(output)

>>>[1, 2, 3, 4, 5, 6, 7]

对我确实经历过这一次。。我不知道哪一个更快,但将列表转换为字符串并以这种方式将其展平似乎是一种糟糕的做法。例如,该函数将用于包含任何项目的列表,而如果其中一个项目是字符串且包含
,则代码将失败['
,'
字符。是的……你说得对..谢谢请浏览、和,看看这个网站是如何工作的,并帮助你改进你当前和未来的问题,这可以帮助你获得更好的答案。我们希望你在这里发布问题之前做适当的研究。使用问题的标题可以轻松地这就是解决方案。