简体   繁体   中英

Python: How can I turn every negative number into a zero?

I'm trying an exercise that wants me to return a new list that contains all the same elements except the negative numbers which are turned into zeros in the returned list.

I have used a for loop to loop through the parameter list and if the number is below 0, I would append it to a new list but times it by 0. However, I get weird outputs such as empty lists. For example, the code below should print:

  1. [0, 0, 9, 0, 0, 34, 1]

  2. [9, 34, 1]

  3. [0, 0, 0]

Please stick to using list methods thanks.

The code:

def get_new_list_no_negs(num_list):
    new_list = []
    for i in range(len(num_list)):
        if i < 0:
            new_list.append(num_list[i] * 0)
    return new_list

def main():
    print("1.", get_new_list_no_negs([-3, -6, 9, 0, 0, 34, 1]))
    print("2.", get_new_list_no_negs([9, 34, 1]))
    print("3.", get_new_list_no_negs([-9, -34, -1]))
main()

This should do:

def get_new_list_no_negs(num_list):
    return [max(num, 0) for num in num_list]

the max function is a python builtin that will return the largest between the passed numbers.

Try this

l = [-2, -1, 0, 1, 2]

# this
l = [i for i in l if i > 0 else 0]
# or
l = [max(i, 0) for i in l]

The enumerate() function adds a counter to an iterable.

So for each element in a cursor, a tuple is produced with (counter, element); the for loop binds that to row_number and row, respectively.

l = [-2, -1, 0, 1, 2]

for index, value in enumerate(l):
    if value < 0:
        l[index] = 0

print(l)

O/P:

[0, 0, 0, 1, 2]

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