猿问

元素列表比较

我有一个问题,我有点难以解释,所以我将使用大量示例来帮助大家理解,看看是否可以帮助我。


假设我有两个列表,其中包含两个人评分从最佳到最差的书名。User1 评分lstA和 user2 评分lstB


lstA = ['Harry Potter','1984','50 Shades','Dracula']

lstB = ['50 Shades','Dracula','1984','Harry Potter']

用户一认为“哈利波特”比“德古拉”好(HP指数为0,德古拉指数为3)


用户二认为'哈利波特'比德古拉更糟糕,(HP指数为3,德古拉指数为1)


在这种情况下,返回一个元组('Harry Potter', 'Dracula')[('Dracula', 'Harry Potter')也可以]


用户一也将“50 种色调”评为“50 种色调”好于“德古拉”,用户 2 也将“50 种色调”评为“50 种色调”好于“德古拉”(分别为指数 2、3 和 0、1)。在这种情况下,什么也不会发生。


程序的最终结果应该返回一个元组列表,所以,


[('Harry Potter','50 Shades'), ('Harry Potter','Dracula'), ('Harry Potter','1984'), ('1984', '50 Shades'), ('1984','Dracula')]

有人可以帮我指出正确的方向来提出一个给出所有元组的算法吗?


慕码人2483693
浏览 201回答 3
3回答

慕虎7371278

首先用数学公式表达你的逻辑。对于长度为 2 的所有组合,给定索引idx_a1, idx_a2和idx_b1, idx_b2,如果sign(idx_a1 - idx_a2) != sign(idx_b1 - idx_b2),记录组合。下面的内容效率不高,但它显示了将此逻辑转换为代码的一种方法:from itertools import combinationslstA = ['Harry Potter','1984','50 Shades','Dracula']lstB = ['50 Shades','Dracula','1984','Harry Potter']def sign(x):&nbsp; &nbsp; """Return +1 if integer is positive, -1 if negative"""&nbsp; &nbsp; return (x > 0) - (x < 0)res = []for a, b in combinations(lstA, 2):&nbsp; &nbsp; idx_a1, idx_a2 = lstA.index(a), lstA.index(b)&nbsp; &nbsp; idx_b1, idx_b2 = lstB.index(a), lstB.index(b)&nbsp; &nbsp; if sign(idx_a1 - idx_a2) != sign(idx_b1 - idx_b2):&nbsp; &nbsp; &nbsp; &nbsp; res.append((a, b))[('Harry Potter', '1984'),&nbsp;('Harry Potter', '50 Shades'),&nbsp;('Harry Potter', 'Dracula'),&nbsp;('1984', '50 Shades'),&nbsp;('1984', 'Dracula')]
随时随地看视频慕课网APP

相关分类

Python
我要回答