如何以最有效的方式判断组合列表中的任何元素是否位于特定集合中?

2024-04-26 03:28:46 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是我所说的问题的意思:

j = [1,2,3,4,5,6,7]
k = [1,2,3,4,5,6,7]

#I want to generate all possible pairs of pairs with these two lists, for 
example: 
p1 = (1,1)
p2 = (2,2)
pairA = (p1,p2) # (1,1),(2,2)
#This is what i mean by pair of pair

#This is what I've got so far:

sA = set()         #this has a lot of pairs of pairs in it
sA.add(...)
#...

for item in permutations(j):
    for m1,m2 in combinations(zip(item,k),2):
           if (m1,m2) in sA:   # I want to know quickly 
                               # if any pair(of pairs) 
                               # the combination produces 
                               # is in set sA
               #do stuff
           else:
               #do some other stuff

我的代码的这一部分随着列表j、k中元素数量的增加而严重扩展。我想知道python中是否有具体的方法可以使它在性能上更高效或风格上更简洁。我觉得它很笨拙

任何想法和建议都将不胜感激!提前谢谢


Tags: oftoinforissathisitem