[英]Python retrieve values in list from set of tuples
Suppose I have a ordered list here called T假设我在这里有一个名为 T 的有序列表
T = ['foo', 'bar', 'cad']
I then have a set M containing tuples.然后我有一个包含元组的集合 M。
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对于 T 中的每个项目,我想在 M 中找到相应的元组对。所以我的 output 看起来像下面的列表
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.我尝试了这个集合理解,但这当然只是迭代了按 M 顺序定义的元素,我需要按 T 顺序定义它。
answer = [ a for (a,b) in R if b in T ]
As a follow up question, say my M looked like:作为后续问题,假设我的 M 看起来像:
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?
纯粹是列表、集合和元组?
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']
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.你可以试试这个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.