Aamir Khan
Aamir Khan

Reputation: 57

Python: Append new tuples where not exists in an list

I have three lists. What I want to do is look for 3rd item in TempTree and if this item is not present in the Set then I want to append this third item into STree.

I will be using a for loop TempTree[i] from i[2:].

Given Data:

TempTree = [(3.0, 5.0), (1.0, 7.0), (5.0, 4.0), (3.0, 4.0), (0.0, 7.0), (1.0, 2.0), (7.0, 8.0), (2.0, 3.0), (8.0, 6.0), (0.0, 1.0), (2.0, 5.0), (2.0, 8.0), (6.0, 5.0), (7.0, 6.0)]
Set = [(3.0, 5.0), (5.0, 3.0), (1.0, 7.0), (7.0, 1.0)]
SpanningTree = [(3.0, 5.0), (1.0, 7.0)]

My Code:

for x in TempTree[2]:
    for y in Set:
        if x != y:
            SpanningTree.append(TempTree[2])
print(SpanningTree)

My result:

[(3.0, 5.0), (1.0, 7.0), (5.0, 4.0), (5.0, 4.0), (5.0, 4.0), (5.0, 4.0), (5.0, 4.0), (5.0, 4.0), (5.0, 4.0), (5.0, 4.0)]

Required Result:

[(3.0, 5.0), (1.0, 7.0), (5.0, 4.0)]

Upvotes: 1

Views: 1451

Answers (2)

noamgot
noamgot

Reputation: 4091

obviously, you are looking in TempTree[2], i.e you do not check the tuple, but each number inside it (5.0, 4.0). in this case, of course x!=y because x is a float and y is a tuple, hence you get 2 * 4 additions of the tuple. what you should do (did not check it, but it's the main idea):

for x in Set:
    if x != TempTree[2]:
            SpanningTree.append(TempTree[2])
            break
print(SpanningTree)

also, better use python Set type and not List to prevent multiple occurences.

Upvotes: 1

Andrii Rusanov
Andrii Rusanov

Reputation: 4606

is it what are you looking for?

if TempTree[2] not in Set:
    SpanningTree.append(TempTree[2])

And in your code on each iteration on Set you check that current element doesn't equal to TempTree[2] and append it every time to SpanningTree(instead of check and append once).

Upvotes: 1

Related Questions