给出两个列表:
a = [3,4,5,5,5,6]
b = [1,3,4,4,5,5,6,7]
我想找到“overlap”:
c = [3,4,5,5,6]
如果可能的话,我还希望能够提取出a和b中不属于c的“剩余部分”。
a_remainder = [5,]
b_remainder = [1,4,7,]
注意:a 中有三个 5,b 中有两个。 a 中只有一个 4,而 b 中有两个。 结果列表 c 应该包含两个 5(受 b 列表限制)和一个 4(受 a 列表限制)。
这给了我想要的结果,但我不禁觉得可能有更好的方法。
import copy
a = [3,4,5,5,5,6]
b = [1,3,4,4,5,5,6,7]
c = []
for elem in copy.deepcopy(a):
if elem in b:
a.pop(a.index(elem))
c.append(b.pop(b.index(elem)))
# now a and b both contain the "remainders" and c contains the "overlap"
在另一个方面,除了“overlap”和“remainder”,有没有更准确的名称来描述我所询问的内容?
list(a)
代替copy.deepcopy(a)
。 - Rosh Oxymorona_remainder = [5,]
,对吧? - Andrew Jaffea[:]
替代copy.deepcopy(a)
。 - nmichaels