zelenov aleksey zelenov aleksey - 1 year ago 118
Python Question

how to check list before adding items?

I have a list of [i,j] values:

lst = [[1,2],[1,3],[3,4],[4,6]]
#[1,2] means that i=1 and j=2

and add new elenemt
, for example
, how can I add values to my lst by condition

(add element
only if
does not exists in a set)

So element
should not be added, because

Thanks in advance for any help!

Answer Source

You could just iterate the list and check whether for any of the items (i,j) in the list, i is the same as b in the item (a,b) you want to add. (At least that's how I understood your condition, but if the condition is slightly different, this should be easy to adapt accordingly.)

def cond_add(lst, item):
    a, b = item
    if not any(i == b for (i, j) in lst):

lst = [[1,2],[1,3],[3,4],[4,6]]
cond_add(lst, [6,1])
cond_add(lst, [6,5])

If you want to add multiple elements, it would pay to create a set from the first elements, so you can do the check in constant time for each individual item. (You could do the same for adding individual elements, but you'd have to update the set after each item.)

def cond_add_many(lst, items):
    first = set(i for (i, j) in lst)
    lst.extend((a,b) for (a,b) in items if b not in first)

lst = [[1,2],[1,3],[3,4],[4,6]]
cond_add_many(lst, [[6,1], [6,5]])

Afterwards, in both cases, lst is [[1, 2], [1, 3], [3, 4], [4, 6], (6, 5)]

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download