user6822657
user6822657

Reputation:

How to find some specific element in a set?

Given some set of tuples (x,y):

set([(1,2),(3,4),(3,2),(1,4)])

How do I find each tuple with the property (1,z) in the set?

In this example the edges (1,2),(1,4).

EDIT: Is there some other data structure that would support such a request?

Upvotes: 0

Views: 44

Answers (1)

Kasravnd
Kasravnd

Reputation: 107287

Use a comprehension (set or list):

In [145]: st = set([(1,2),(3,4),(3,2),(1,4)])

In [146]: [(i, j) for i, j in st if i == 1]
Out[146]: [(1, 2), (1, 4)]

In [147]: {(i, j) for i, j in st if i == 1}
Out[147]: {(1, 2), (1, 4)}

Or if you don't want the result in a container, i.e. you just want to loop over the results, etc. you can use a function approach by using the built-in filter function:

result = filter(lambda x: x[0] == 1, st)

Upvotes: 2

Related Questions