开发者

How to remove values from item list

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开发者_如何学JAVA do i remove the item list with value 0.0 and return

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


[x for x in rank_item if x[1] != 0.0]


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 ]


>>> [i for i in rank_item if i[1]]
[(9, 0.9999999974599665), (8, 0.999999967968611), (1, 0.999999967968611)]


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜