简体   繁体   English

在Python中将多维列表转换为1D列表

[英]Convert multi-dimensional list to a 1D list in Python

A multidimensional list like l=[[1,2],[3,4]] could be converted to a 1D one by doing sum(l,[]) . l=[[1,2],[3,4]]这样的多维列表可以通过sum(l,[])转换为1D。 Can anybody please explain how that happens? 任何人都可以解释一下这是怎么回事?

A responder said that this technique could only be used to "flatten" a 2D list -- that it wouldn't work for higher multidimensional lists. 响应者说,这种技术只能用于“压扁”2D列表 - 它不适用于更高的多维列表。 But it does, if repeated. 但如果重复,它确实如此。 For example if A is a 3D-list, then sum(sum(A),[]),[]) will flatten A to a 1D list. 例如,如果A是3D列表,则sum(sum(A),[]),[])将A压缩为1D列表。

If your list nested is, as you say, "2D" (meaning that you only want to go one level down, and all 1-level-down items of nested are lists), a simple list comprehension: 如果您所说的nested列表是“2D”(意味着您只想向下一级,并且nested所有1级向下项目都是列表),那么简单的列表理解:

flat = [x for sublist in nested for x in sublist]

is the approach I'd recommend -- much more efficient than sum ming would be ( sum is intended for numbers -- it was just too much of a bother to somehow make it block all attempts to "sum" non-numbers... I was the original proposer and first implementer of sum in the Python standard library, so I guess I should know;-). 是我推荐的方法 - 比sum更有效( sum是用于数字 - 以某种方式让它阻止所有“加”非数字的尝试太麻烦了...我是Python标准库中最初的提议者和sum第一个实现者,所以我想我应该知道;-)。

If you want to go down "as deep as it takes" (for deeply nested lists), recursion is the simplest way, although by eliminating the recursion you can get higher performance (at the price of higher complication). 如果你想“尽可能深入”(对于深度嵌套的列表),递归是最简单的方法,尽管通过消除递归可以获得更高的性能(以更高的复杂性为代价)。

This recipe suggests a recursive solution, a recursion elimination, and other approaches (all instructive, though none as simple as the one-liner I suggested earlier in this answer). 这个方法提出了一个递归解决方案,一个递归消除和其他方法(所有这些方法都很有用,但没有一个像我在本回答中提到的单线程一样简单)。

sum adds a sequence together using the + operator. sum使用+运算符将序列加在一起。 eg sum([1,2,3]) == 6 . 例如sum([1,2,3]) == 6 The 2nd parameter is an optional start value which defaults to 0. eg sum([1,2,3], 10) == 16 . 第二个参数是一个可选的起始值,默认为0.例如sum([1,2,3], 10) == 16

In your example it does [] + [1,2] + [3,4] where + on 2 lists concatenates them together. 在你的例子中它有[] + [1,2] + [3,4] ,其中+ 2个列表将它们连接在一起。 Therefore the result is [1,2,3,4] 因此结果是[1,2,3,4]

The empty list is required as the 2nd paramter to sum because, as mentioned above, the default is for sum to add to 0 (ie 0 + [1,2] + [3,4] ) which would result in unsupported operand type(s) for +: 'int' and 'list' 需要空列表作为sum的第2个参数,因为如上所述,默认值是将sum加到0(即0 + [1,2] + [3,4] ),这将导致不支持的操作数类型( s)for +:'int'和'list'

This is the relevant section of the help for sum : 这是sum帮助的相关部分:

sum(sequence[, start]) -> value sum(sequence [,start]) - > value

Returns the sum of a sequence of numbers (NOT strings) plus the value of parameter 'start' (which defaults to 0). 返回一系列数字(非字符串)加上参数'start'的值(默认为0)。

Note 注意

As wallacoloo comented this is not a general solution for flattening any multi dimensional list. 正如wallacoloo所述,这不是用于展平任何多维列表的一般解决方案。 It just works for a list of 1D lists due to the behavior described above. 由于上述行为,它仅适用于1D列表的列表。

Update 更新

For a way to flatten 1 level of nesting see this recipe from the itertools page: 有关展平1级嵌套的方法,请参阅itertools页面中的此配方:

def flatten(listOfLists):
    "Flatten one level of nesting"
    return chain.from_iterable(listOfLists)

To flatten more deeply nested lists (including irregularly nested lists) see the accepted answer to this question (there are also some other questions linked to from that question itself.) 要展平更深层次的嵌套列表(包括不规则嵌套列表),请参阅此问题的已接受答案 (还有一些与该问题本身相关的其他问题。)

Note that the recipe returns an itertools.chain object (which is iterable) and the other question's answer returns a generator object so you need to wrap either of these in a call to list if you want the full list rather than iterating over it. 请注意,配方返回一个itertools.chain对象(可迭代),另一个问题的答案返回一个generator对象,因此如果您想要完整列表而不是迭代它,则需要将其中任何一个包装在list调用中。 eg list(flatten(my_list_of_lists)) . 例如list(flatten(my_list_of_lists))

It looks to me more like you're looking for a final answer of: 在我看来,更像是在寻找最终答案:

[3, 7]

For that you're best off with a list comprehension 为此,你最好有一个列表理解

>>> l=[[1,2],[3,4]]
>>> [x+y for x,y in l]
[3, 7]

For any kind of multidiamentional array, this code will do flattening to one dimension : 对于任何类型的多元数组,此代码将展平为一个维度:

def flatten(l):
    try:
        return flatten(l[0]) + (flatten(l[1:]) if len(l) > 1 else []) if type(l) is list else [l]
    except IndexError:
        return []

I wrote a program to do multi-dimensional flattening using recursion. 我写了一个程序来使用递归进行多维展平。 If anyone has comments on making the program better, you can always see me smiling: 如果有人对改进程序有任何意见,你总能看到我微笑:

def flatten(l):
    lf=[]
    li=[]
    ll=[]
    p=0
    for i in l:
        if type(i).__name__=='list':
           li.append(i)
        else:
           lf.append(i)
    ll=[x for i in li for x in i]
    lf.extend(ll)

    for i in lf:
        if type(i).__name__ =='list':
           #not completely flattened
           flatten(lf)
        else:
           p=p+1
           continue

    if p==len(lf):
       print(lf)

+运算符连接列表,起始值为[]空列表。

I've written this function: 我写过这个函数:

def make_array_single_dimension(l):
    l2 = []

    for x in l:
        if type(x).__name__ == "list":
            l2 += make_array_single_dimension(x)
        else:
            l2.append(x)

    return l2

It works as well! 它也有效!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM