dimanche 29 septembre 2019

How to save an element from a list as a whole after an if-statement

Hello stackoverflow community :-)

I want to save elements of a list as a whole in a new list.

My new task is to transform nested lists into a flat one. My plan was to take out the elements of each list and save them into a variable. And in the end to put the variables together, so that there is just a flat list at the end.

I have two problems:

1) The index-3 element ('99999') isn't saved as a whole in the list of the new variable. This problem is the topic of this question.

2) I can not separate the nested list [66, 77, 88] from the higher list ['4', '5',[]], but this is not the topic of this question

So here is the code of the nested list and of my if-statement:

nested_list = ['1', '2', '3', '99999',['4', '5',[66, 77, 88]]]
y = []
for i in nested_list:
    if type(i) != (list or tuple):
        y += i
print(y)

I want the index=3 element (the string '99999') be saved in the variable y as a whole string and not splitted into the single parts '9', '9', '9', '9', '9'

I want:

print(y)
['1', '2', '3', '99999']

I get:

print(y)
['1', '2', '3', '9', '9', '9', '9', '9']

I can't solve the problem with saving into a string (y = ' '), because than I get the result:

print(y)
12399999

and if I would transform the string to a list

y = list(y)

I get the same unwanted result

['1', '2', '3', '9', '9', '9', '9', '9']

I think the solution lies in the action code after the if-statement

y += i

Is there a command, which takes the whole element into y? I tried y += sum(i) but of course this didn't work, because

1) it adds up all numbers like int, floats, etc.., not strings

2) I don't need to add 9+9+9+9+9=45, but I need just the whole string in my new list y.

I've searched a lot on Google for such a command, but didn't found something that would help me.

I have to say, that I am a code Newbee and learning Python for just 2 weeks.

Best regards Matthias

Aucun commentaire:

Enregistrer un commentaire