Stiven G
Stiven G

Reputation: 215

Index over a set, I get two sets and not one

I thought the following code would work the way I expcted.

p1 = [
    ({1}, (0,0)),
    ({2}, (0,0)),
    ({3},(0,0),
]
p2 = [
    ({1,2}, (1,0)),
    ({3}, (0,0)),
]
for k in range(len(p1)):
    m = set()
    for l in range(len(p2)):
        if p1[k] != p2[l]:
           m = m.union(
               set([min(p1[k][0])]))
    print(m)

What I should be getting is {1,2}, but I get

Set([1])
Set([2])

I also get an error message saying:

'set' object does not support indexing

and I don't know if I should be using some other command.

I am real grateful for any help I can get. I have thought about it for some time and have not been able to fix this.

Upvotes: 0

Views: 50

Answers (1)

AChampion
AChampion

Reputation: 30258

It is unclear what you are trying to do, but just fixing your errors does not return you expected output. Using itertools.product() instead of nested for loops:

p1=[({1}, (0,0)), ({2}, (0,0)), ({3}, (0,0))]
#                                  ^^^^ a tuple now
p2=[({1,2}, (1,0)), ({3}, (0,0))]

In []
import itertools as it

m = set()
for k, l in it.product(p1, p2):
    if k != l:
        m.add(min(k[0]))
print(m)

Out[]:
{1, 2, 3}

Making a big assumption but if you meant to go through these lists both at the same time you would use zip(p1, p2), e.g.:

In []:
m = set()
for k, l in zip(p1, p2):
    if k != l:
        m.add(min(k[0]))
print(m)

Out []:
{1, 2}

Upvotes: 1

Related Questions