Python: removing negatives from a list of numbers

The question is removing negative numbers.

When executed remove_negs([1, 2, 3, -3, 6, -1, -3, 1]), the result of: [1, 2, 3, 6, -3, 1]. The result should be [1, 2, 3, 6, 3, 1]. what happens if there are two negative numbers in the line (for example, -1, -3), then the second number will not be deleted. def main (): numbers = input ("Enter the list of numbers:") remove_negs (numbers)

def remove_negs(num_list): 
  '''Remove the negative numbers from the list num_list.'''
    for item in num_list: 
        if item < 0: 
           num_list.remove(item) 

    print num_list

main()
+4
source share
7 answers

, , (. ). :

num_list = [item for item in num_list if item >= 0]

, num_list. " "

num_list[:] = ...

, , num_list. .

+10

:

>>> a = [ 1, 2, 3, -3, 6, -1, -3, 1]
>>> [x for x in a if x >= 0 ]
[1, 2, 3, 6, 1]

, :

def remove_negs(num_list): 
    r = num_list[:]
    for item in num_list: 
        if item < 0: 
           r.remove(item) 
    print r

, :

>>> remove_negs([ 1, 2, 3, -3, 6, -1, -3, 1])
[1, 2, 3, 6, 1]

, r = num_list[:] num_list. , r, , .

: Python . Python , r num_list, , [1, 2, 3, 6, 1]. . :

r = num_list

r num_list . r, num_list, . :

r = num_list[:]

python num_list, . - python num_list. , [:] , , num_list , python . r. , r mum_list . r num_list, .

, python : Python

< > :

>>> a = [ 1, 2, 3, -3, 6, -1, -3, 1]
>>> b = a   # a and b now point to the same place
>>> b.remove(-1) 
>>> a
[1, 2, 3, -3, 6, -3, 1]

:

>>> a = [ 1, 2, 3, -3, 6, -1, -3, 1]
>>> b = a[:] # a and b now point to different data
>>> b
[1, 2, 3, -3, 6, -1, -3, 1]
>>> b.remove(-1)
>>> b
[1, 2, 3, -3, 6, -3, 1]
>>> a
[1, 2, 3, -3, 6, -1, -3, 1]
+5

arshajii :

. , .

- , , :

[1, 2, 3, 6, 3, 1]

" " , . , -3, 3, ? , :

for index, item in enumerate(num_list): 
    if item < 0: 
       num_list[index] = -item

... , arshajii's:

num_list = [-item if item < 0 else item for item in num_list]

abs, - , :

num_list = [abs(item) for item in num_list]

, [1, 2, 3, 3, 6, 1, 3, 1], ... , , .

+1

filter( lambda x: x>0, [ 1, 2, 3, -3, 6, -1, -3, 1])
[1, 2, 3, 6, 1]
+1

variable operator non-variable yoda =)

>>> [i for i in x if 0 <= i]
[1, 2, 3, 6, 1]
0

, ,

def remove_negs(somelist):
    for each in somelist:
        if each < 0:
            somelist[somelist.index(each)] = -each
    print(somelist)

r ([- 2,5,11, -1])

[2,5,11,1]

0

, :

import numpy as np

x = [1, 2, 3, -3, 6, -1, -3, 1] # raw data
x = np.array(x) # convert the python list to a numpy array, to enable 
                  matrix operations 
x = x[x >=0] # this section `[x >=0]` produces vector of True and False 
               values, of the same length as the list x
             # as such, this statement `x[x >=0]` produces only the 
               positive values and the zeros

print(x)   
[1 2 3 6 1] # the result
0

All Articles