tags:

views:

123

answers:

5

Hi, I am new to python. I have a item list looks like this:

rank_item = [ 
    (9, 0.99999999745996648), 
    (8, 0.99999996796861101), 
    (1, 0.99999996796861101), 
    (10, 0.0) ]

The question is how do i remove the item list with value 0.0 and return

[(9, 0.99999999745996648), (8, 0.99999996796861101), (1, 0.99999996796861101)]
+5  A: 

Use list.remove - which will modify your rank_item list in-place:

 rank_item.remove( (10, 0.0) )

rank_item will contain:

[(9, 0.99999999745996648), (8, 0.99999996796861101), (1, 0.99999996796861101)]

Or, if you want to remove all tuples from your list, which have a the value 0.0 at position 1, you can try a list comprehension, e.g.:

[ x for x in rank_item if x[1] != 0.0 ]
The MYYN
Note: this will modify the `rank_item` object.
Karmastan
+5  A: 
[x for x in rank_item if x[1] != 0.0]
Ignacio Vazquez-Abrams
Note: this will create a new list without changing `rank_item`
Karmastan
+3  A: 
>>> [i for i in rank_item if i[1]]
[(9, 0.9999999974599665), (8, 0.999999967968611), (1, 0.999999967968611)]
SilentGhost
+1  A: 

For a more general case, you can use a list comprehension:

new_list = [(a, b) for a, b in old_list if b != 0]

This would only return the tuples where the second element is different from zero; you can adjust this behavior to fit your needs.

This approach favors a clear labeling of each element, as opposed to using an index.

Arrieta
+1  A: 

Speed test:

>>> import timeit
>>> it = lambda : list(filter(lambda x: x[1]!=0, rank_item))
>>> timeit.timeit(it)
3.7716277663630535

>>> it2 = lambda: [x for x in rank_item if x[1] != 0.0]
>>> timeit.timeit(it2)
1.2550897693390652

>>> it3 = lambda: [i for i in rank_item if i[1]]
>>> timeit.timeit(it3)
1.147179730129892

>>> it4 = lambda: list(itertools.takewhile(lambda x: x[1] != 0, rank_item))
>>> timeit.timeit(it4)
3.8272935335999136
Selinap