【问题标题】:Flattened List of Lists [duplicate]列表的扁平列表[重复]
【发布时间】:2021-05-06 07:19:12
【问题描述】:

我正在寻找一个包含多个嵌套列表的列表:

list1 = [[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

【问题讨论】:

  • 请通过intro tourhelp centerhow to ask a good question 了解本网站的运作方式并帮助您改进当前和未来的问题,从而帮助您获得更好的答案。我们希望您在此处发布问题之前进行适当的研究。使用问题的标题很容易找到解决方案。

标签: python list dictionary tuples flatten


【解决方案1】:

试试这个:

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]

【讨论】:

  • 是的..我确实经历过这个..哪个跑得更快??
  • 我不知道哪个更快,但是将列表转换为字符串并以这种方式展平似乎是一种不好的做法。例如,该函数适用于包含任何项目的列表,而如果其中一个项目是字符串并且包含 '['',' 字符,则您的代码将失败。
  • 是的......你是对的......谢谢
猜你喜欢
  • 2012-07-01
  • 2016-01-14
  • 1970-01-01
  • 2017-02-27
  • 2019-11-29
  • 2017-09-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多