简体   繁体   中英

Checking elements in a list of integers for positive or negative values

I have a predetermined created list of integers that I want to traverse and append "positive" or "negative" if the value meets the criteria. However it is throwing "TypeError: '>' not supported between instances of 'str' and 'int' on the first line of my if statement. I have seen this error before when getting user input and must convert the input to a int, but my list is already an integer, so I am confused on what I need to fix. It is throwing the error on if lst[i] > 0:

lst = [-2, 1, -2, 7, -8, -5, 0, 5, 10, -6, 7]

for i in lst:
    if lst[i] > 0:
        lst.append("positive")
    elif lst[i] < 0:
        lst.append("negative")
    else:
        lst.append("zero")

You should do like this:

lst = ["positive" if el > 0 else "negative" if el < 0 else "zero" for el in [-2, 1, -2, 7, -8, -5, 0, 5, 10, -6, 7]]

Much faster and clean way to create what you need.

return:

['negative', 'positive', 'negative', 'positive', 'negative', 'negative', 'zero', 'positive', 'positive', 'negative', 'positive'] 
[('negative', 'zero', 'positive')[((n > 0) - (n < 0))+1] for n in lst]

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