简体   繁体   English

根据参数取消嵌套列表一定次数

[英]Un-nesting a list a certain number of times based on parameter

I am trying to unnest a list n number of times, where n is passed into the function.我试图取消嵌套列表 n 次,其中 n 被传递到 function 中。 There can only be one value within the innermost list, its just the problem of removing brackets最里面的列表只能有一个值,就是去掉括号的问题

I have tried:我努力了:

def nest(x,n):
    newlist = [x]
    flatlist=[]
    if n > 0:
        for counter in range(n-1):
            newlist = [newlist]
        return newlist
    elif n<0:
        for sublist in x:
            for item in sublist:
                print(item)

        return flatlist
    else:
        return x

print(nest([[["hello"]]], -3))

but this only removes the outermost list irrespective of the number of lists this should unnest.但这只会删除最外面的列表,而不管应该取消嵌套的列表数量。 The output of this is "[["hello"]]" output 是"[["hello"]]"

I don't really get the logic in your code when the n is negative, but if I understood the problem correctly, and you simply want to add/remove the brackets around your input list, the following code will do it:n为负数时,我并没有真正了解您的代码中的逻辑,但是如果我正确理解了问题,并且您只想添加/删除输入列表周围的括号,则以下代码将执行此操作:

def nest(x, n):
    if n > 0:
        for _ in range(n):
            x = [x]
    if n < 0:
        for _ in range(-n):
            x = x[0]    
    return x

Examples:例子:

print(nest([[["hello"]]], 0))
# [[['hello']]]

print(nest([[["hello"]]], 2))
# [[[[['hello']]]]]

print(nest([[["hello"]]], -2))
# ['hello']

Note that if you specify n greater than the number of brackets, this can produce an unexpected result if the inner element is a string:请注意,如果您指定的n大于括号的数量,如果内部元素是字符串,这可能会产生意外结果:

print(nest([[["hello"]]], -4))
# h

Probably, you wouldn't want that, so we need either simply return the inner element in this case, or raise an error:可能你不希望这样,所以我们需要在这种情况下简单地返回内部元素,或者引发错误:

def nest(x, n):
    if n > 0:
        for _ in range(n):
            x = [x]
    if n < 0:
        for _ in range(-n):
            if not isinstance(x, list):
                break  # or raise ValueError('Not enough nested levels to unpack')
            x = x[0]    
    return x

print(nest([[["hello"]]], -4))
# hello

This could work, you might need to adapt it.这可能有效,您可能需要对其进行调整。

def unnest(x):
    x2 = []
    for i in x:
        for j in i:
            x2.append(j)
    return x2


def nest(x,n):
    x2 = x
    for i in range(n):
        x2 = unnest(x2)
    return x2

This will nest as you want to:这将按照您的意愿嵌套:

lst1 = [[["hello"]]]
str1 = 'hello'

def nest(element, n):
    return [nest(element, n - 1)] if n else element

print(nest(str1, 5))
# [[[[['hello']]]]]

This will unpack lists of lists of lists... recursively.这将解包列表列表的列表......递归。

def flatten_list(lst):
    """returns flat list"""
    if isinstance(lst, (list, tuple)):
        if len(lst) == 0:
            return []
        first, rest = lst[0], lst[1:]
        return flatten_list(first) + flatten_list(rest)
    else:
        return [lst]

def flatten_to_string(lst):
    """extracts flat list to string"""
    return flatten_list(lst)[0]


print(flatten_to_string([[["hello"]]]))
# hello

print(flatten_list([[[[[["hello"]]], [[["hello"]]]]]]))
# ['hello', 'hello']

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

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