Home > Back-end >  Python - appending to a list in for loop after if statement
Python - appending to a list in for loop after if statement

Time:12-21

I have a list of list elements that I'm modifying. And after that modification I want to put them into a list that have the same structure as the original one:

list_data_type = [
[['void1']], [['uint8']], [['uint8'], ['uint32']], [['void2']], [['void3']], [['void4']], [['void5']]
]

Firstly I check for elements that have more than one element. So in this case that would be element with index number = 2. Then I change it into a string, strip it from brackets [] and " " marks and convert it to a list. Then I take other elements and do the same thing. After conversion I want to create a new list with those elements, but without unnecessary symbols. So my desired output would look like this:

list_data_converted = [
['void1'], ['uint8'], ['uint8', 'uint32'], ['void2'], ['void3'], ['void4'], ['void5']
]

Conversion works and I can print out elements, but I have a problem with appending them to a list. My code saves only last value from original list:

def Convert(string):
    li = list(string.split(" "))
    return li

for element in list_data_type:
    if type(element) == list:
        print("element is a:", element, type(element))
        if len(element) > 1:
            id_of_el = list_data_type.index(element)
            el_str = str(element).replace('[', '').replace("'", '').replace("'", '').replace(']', '').replace(',', '')
            el_con = Convert(el_str)
        elif len(element <= 1):
            elements_w_1_el = element
            list_el = []
            for i in range(len(elements_w_1_el)):
                el_str_2 = str(element).replace('[', '').replace("'", '').replace("'", '').replace(']', '').replace(',', '')
                list_el.append(elements_w_1_el[i])

And my out instead looking like "list_data_converted", has only one element - ['void5']. How do I fix that?

CodePudding user response:

Converting a list to a string to flatten it is a very... cumbersome approach. Try simple list-comprehension:

list_data_type = [[v[0] for v in l] for l in list_data_type]

CodePudding user response:

Type casting the list into a string and then replacing the characters and then again converting the string into list might be bad way to achieve what you're doing.

Try this :

def flatten(lst):
    if lst == []:
        return lst
    if isinstance(lst[0], list):
        return flatten(lst[0])   flatten(lst[1:])
    return lst[:1]   flatten(lst[1:])

list_data_converted = [flatten(element) for element in list_data_type]

This actually flattens any list item inside list_data_type and keep them in a single list. This should work with any depth of list inside list. Output print(list_data_converted) would give the following :

[
    ['void1'], ['uint8'], ['uint8', 'uint32'], ['void2'], ['void3'], ['void4'], ['void5']
]
  • Related