3 回答

TA贡献1802条经验 获得超4个赞
首先用数学公式表达你的逻辑。对于长度为 2 的所有组合,给定索引idx_a1, idx_a2和idx_b1, idx_b2,如果sign(idx_a1 - idx_a2) != sign(idx_b1 - idx_b2),记录组合。
下面的内容效率不高,但它显示了将此逻辑转换为代码的一种方法:
from itertools import combinations
lstA = ['Harry Potter','1984','50 Shades','Dracula']
lstB = ['50 Shades','Dracula','1984','Harry Potter']
def sign(x):
"""Return +1 if integer is positive, -1 if negative"""
return (x > 0) - (x < 0)
res = []
for a, b in combinations(lstA, 2):
idx_a1, idx_a2 = lstA.index(a), lstA.index(b)
idx_b1, idx_b2 = lstB.index(a), lstB.index(b)
if sign(idx_a1 - idx_a2) != sign(idx_b1 - idx_b2):
res.append((a, b))
[('Harry Potter', '1984'),
('Harry Potter', '50 Shades'),
('Harry Potter', 'Dracula'),
('1984', '50 Shades'),
('1984', 'Dracula')]
添加回答
举报