开发者

How can I check if there exist any reverse element in list of dict without looping on it

My list is like

l1 = [ {k1:v1} , {k2:v2}, {v1:k1} ]

Is there开发者_开发百科 any better way to check if any dictionary in the list is having reverse pair?


I would suggest to transform the dictionaries in tuple and put the tuple in a set. And look in the set if the reverse tuple is in the set. That would have a complexity of O(n) instead of O(n^2).


This code seems to work without loop:

k1 = 'k1'
k2 = 'k2'
v1 = 'v1'
v2 = 'v2'
l1 = [ {k1:v1} , {k2:v2}, {v1:k1} ]

kv = [e.items()[0] for e in l1]
print(kv)

vk = [(v, k) for (k, v) in kv]
print(vk)

result = [(k, v) for (k, v) in kv if (k, v) in vk]
print(result)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜