0

Suppose I have a ordered list here called T

T = ['foo', 'bar', 'cad']

I then have a set M containing tuples.

M = { 
        ('jack', 'bar'), 
        ('bob', 'foo'), 
        ('let', 'cad') 
    }

For every item in T, I want to find the corresponding tuple pair in M. So my output would look like the following list

O = [ 'bob', 'jack', 'let' ]

I tried this set comprehension but this of course just iterated the elements as defined in the order of M, I need to define it in the order of T.

answer = [ a for (a,b) in R if b in T ]

As a follow up question, say my M looked like:

M = { 
        ('bar', 'jack'), 
        ('foo', 'bob'), 
        ('cad', 'let') 
    }

Does this make this easier to solve?

Is it possible to solve this without using a dict? Purely lists, sets and tuples?

4
  • 1
    Your expected output is not possible, in the sense that you expect a set in a specific order, but sets are unordered. Commented May 28, 2021 at 12:31
  • If you need some order, build a list instead of a set Commented May 28, 2021 at 12:32
  • Sorry, typo on my part I want my expected answer to be a List. Commented May 28, 2021 at 12:35
  • @DanielJ if an answer here solves your problem, please accept it Commented May 28, 2021 at 15:48

2 Answers 2

1
T = ['foo', 'bar', 'cad']

M = { 
        ('jack', 'bar'), 
        ('bob', 'foo'), 
        ('let', 'cad') 
    }

d = {k:v for (v,k) in M}

answer = [d[elt] for elt in T]

print(answer)
# ['bob', 'jack', 'let']
Sign up to request clarification or add additional context in comments.

Comments

0
T = ['foo', 'bar', 'cad']
M = { 
        ('jack', 'bar'), 
        ('bob', 'foo'), 
        ('let', 'cad') 
    }

# Solution 1 - Order is different everytime
a = [x for (x, y) in M if y in T]
print(a)

# Solution 2 - Give you answer in same order always
MT = {y:x for (x, y) in M}
a = [MT[i] for i in T]
print(a)

You can try this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.