简体   繁体   中英

How do I append a list with sublists inside of it?

All I need to do is to create 1 list with all these values without sublists.

example = ['a', ['c', 1, 3], ['f', 7, [4, '4']], [{'lalala': 111}]]
newArray = []

def func(array):
    for i in array:
        for z in i:
            newArray.append(z)

print(func(example))

The result here would be: ['a', 'c', 1, 3, 'f', 7, [4, '4'], {'lalala': 111}]. When I add 3rd for it would say that 'int' object is not iterable. Do I need somehow check whether the item is int or string and then skip them? Or am I missing something?

PS I believe this is done with the recursive functions, but I have no clue about them :(

Here is one example of recursive function that flattens your list :

def flatten(l):
    if type(l) is list:
        if not l:
            return []
        if len(l) == 1 :
            return flatten(l[0])
        else:
            return flatten(l[0]) + flatten(l[1:])
    else:
        return [l]

Result is ['a', 'c', 1, 3, 'f', 7, 4, '4', {'lalala': 111}]

Using recursive function. Enjoy!

Code:

example = ['a', ['c', 1, 3], ['f', 7, [4, '4']], [{'lalala': 111}]]
newArray = [] 

def super_extend(v):
        if type(v) is list:
            [super_extend(x) for x in v if x is not None]
        if type(v) is dict:
            {k:super_extend(v) for k,v in v.items() if v is not None}
        if type(v) is str or isinstance(v, int) or isinstance(v, float) :
            newArray.append(v)

super_extend(example)
print(newArray)

Output:

['a', 'c', 1, 3, 'f', 7, 4, '4', 111]
[Finished in 0.078s]

In case you don't want the dictionaries to stay as dictionaries and only want the values. You can use this. But if you want to keep the keys all you need to do is use:

if type(v) is dict:
        {super_extend(v):super_extend(k) for k,v in v.items() if v is not None}

Then the output would be:

['a', 'c', 1, 3, 'f', 7, 4, '4', 'lalala', 111]
[Finished in 0.077s]

Using a recursive generator function:

def flatten(l):
    if isinstance(l, list):
        for x in l:
            yield from flatten(x)
    else:
        yield l

>>> list(flatten(example))
['a', 'c', 1, 3, 'f', 7, 4, '4', {'lalala': 111}]

List methods

The list object offers two different methods to add new items to a given list :

  1. list.append(x): Add an item to the end of the list. Equivalent to a[len(a):] = [x].

  2. list.extend(iterable): Extend the list by appending all the items from the iterable. Equivalent to a[len(a):] = iterable.

Example

old_list = ['a', ['c', 1, 3], ['f', 7, [4, '4']], [{'lalala': 111}]]
new_list = []

for element in old_list:
    new_list.extend(element)

print(new_list)

Result

['a', 'c', 1, 3, 'f', 7, [4, '4'], {'lalala': 111}]

Maybe you are looking for something like this:

example = ['a', ['c', 1, 3], ['f', 7, [4, '4']], [{'lalala': 111}]]

def func(array):
    newArray = []
    for i in array:
        if((type(i)==int) or (type(i)==str)):
            newArray.append(i)
        elif(type(i)==dict ):
            keys = i.keys()
            values = i.values()
            newArray.append(keys[0])
            newArray.append(values[0])
        else:
            for z in i:            
                newArray.append(z)
    return newArray

print(func(example))
print(func(func(example)))
print(func(func(func(example))))

result:

['a', 'c', 1, 3, 'f', 7, [4, '4'], {'lalala': 111}]
['a', 'c', 1, 3, 'f', 7, 4, '4', 'lalala', 111]
['a', 'c', 1, 3, 'f', 7, 4, '4', 'lalala', 111]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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