user1977902
user1977902

Reputation:

Checking if first item of a list of list exists in first item of another list of list

for example.

lets consider this is my list

A = [["A1",0],["B1",0],["C1",1],["D1",3]]

and this is the list which i wanna compare it with

B = [["C1",2],["E1",3]]

How do i compare only first index of each list inside the list?. for ex. Searching if first index of any list in list A exists at first index of any list inside List B?

I want to insert all the items from B to A that doesn't have the same first index for any list. so i don't wanna insert ["C1",2] because C1 already exist in list A but ["C1",2] doesn't but i don't care about the second index value.

I hope i was able to explain this problem.

Upvotes: 0

Views: 964

Answers (5)

Adem Öztaş
Adem Öztaş

Reputation: 21446

You can try like this,

>>> A = [["A1",0],["B1",0],["C1",1],["D1",3]]
>>> B = [["C1",2],["E1",3]]
>>>
>>> for item in B:
...     if item[0] not in [item_a[0] for item_a in A]:
...             A.append(item)
...
>>> A
[['A1', 0], ['B1', 0], ['C1', 1], ['D1', 3], ['E1', 3]]

Upvotes: 0

Bharel
Bharel

Reputation: 26901

This should do the trick:

A = [["A1",0],["B1",0],["C1",1],["D1",3]]
B = [["C1",2],["E1",3]]

import operator
A_indexes = set(map(operator.itemgetter(0), A)) # Create a set of indexes for O(1) lookup

# Add to A each item that is present in B but not in indexes.
# At the same time, add in indexes.
A.extend(
    A_indexes.add(item[0]) or item for item in B
    if item[0] not in A_indexes) 

It's the most efficient solution by far. All others are O(n^2).

If you don't care about order, this is also viable:

A = [["A1",0],["B1",0],["C1",1],["D1",3]]
B = [["C1",2],["E1",3]]

import itertools
A = list(dict(itertools.chain(B, A)).items())

Upvotes: 0

senaps
senaps

Reputation: 1525

I have written this code, it work's but i don't think if it's efficient.

for a in range(0, len(A)):
    for b in range(0, len(B)):
        if B[b][0] == A[a][0]:
            print B[b]

And the result of this code is

['C1', 2]

Upvotes: 0

powersof10b
powersof10b

Reputation: 31

I don't know if is in option for you but it would be much easier to use dictionaries here:

A = {"A1":0,"B1":0,"C1":1,"D1":3}
B = {"C1":2,"E1":3}
for B_key in B.keys():
    if not B_key in A.keys():
        A[B_key] = B[B_key]

Upvotes: 1

Sam Marinelli
Sam Marinelli

Reputation: 1119

I don't think there's any kind of automated way of doing this, but you can easily implement it yourself.

for l in B:
    first = l[0]
    found = False
    for m in A:
        if m[0] == first
            found = True
            break
    if not found:
        A.append(l)

Upvotes: 0

Related Questions