Siyah Siyah - 10 months ago 47
Python Question

How to replace elements in list when condition is met

Right now, I am struggling to find a proper answer. Let's say we have this list:

['12', '50', '12', '7', '7', '3', '4', '10', '19', '12']

As you can see, it's a list of strings. I could map this to a list of
, but I won't, because I need to change them back to strings anyway. On the other hand, it would be handy if I would do it because I need to check for a condition.

What do I need? --> I need to change the elements in the list when a certain condition is met. So, for example: if a list in the element is greater than 10, I need to change the element to a certain character like a
plus (+)
or a
minus (-)

Eventually, my list should be something like this:

['+', '+', '+', '-', '-', '-', '-', '+', '+', '+']

So, the concept in my head right now is:

  • Don't convert the string to an int, because I will need to transform them to strings anyway (hence the special characters I was talking about).

  • I need to use a
    for loop
    , because I want to check every element

I'd probably need to use a loop like this:

for score in scores:
if score == "5": # check if element is a 5
score == "+" # make it a plus
score == "-" # make it a minus

Problem: this doesn't work and I don't even know if this is the right way. I can use
and get every element in the list like this, but this wouldn't be efficient nor generic, or would it? What is the best way to transform elements in a list when a certain condition is met?

Can someone point in me the right direction please?

Leo Leo
Answer Source

Try this (assuming you want 10 as the cutoff)

li = ['12', '50', '12', '7', '7', '3', '4', '10', '19', '12'] 

new_list = ['+' if int(el)>10 else '-' for el in li]