元素列表比较 [英] List comparison of element

查看:94
本文介绍了元素列表比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,我很难解释,所以我将使用许多示例来帮助大家理解并了解您是否可以帮助我.

I have a question and it is a bit hard for me to explain so I will be using lots of examples to help you all understand and see if you could help me.

说我有两个列表,其中包含两个人对书名的评价(从最佳到最差).用户1评级为lstA,用户2评级为lstB

Say I have two lists containing book names from best to worst rated by two people. User1 rated lstA, and user2 rated lstB

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

用户认为哈利·波特"比吸血鬼"好(HP为索引0,而吸血鬼为索引3)

User one thinks 'Harry Potter' is better than 'Dracula' (HP is index 0, and Dracula is index 3)

用户二认为哈利·波特"比德古拉更糟(HP为3,德古拉为1)

User two thinks 'Harry Potter' is worse than Dracula, (HP is index 3 and Dracula is index 1)

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

In this case, return a tuple ('Harry Potter', 'Dracula') [('Dracula', 'Harry Potter') is also fine]

用户1的评分也比吸血鬼"好50分,用户2的评分也比吸血鬼"好50分(分别为2、3和0、1).在这种情况下,什么也不会发生.

User one also rated '50 shades' better than 'Dracula' and user two also rated '50 shades' better than 'Dracula' (index 2, 3 and 0, 1 respectively). In this case, nothing happens.

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

The final result of the program should return a list of tuples so,

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

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

Could someone help me to point me in the right direction to come up with an algorithm that gives all the tuples?

推荐答案

首先以数学方式阐述您的逻辑.对于长度为2的所有组合,给定索引idx_a1, idx_a2idx_b1, idx_b2,如果为sign(idx_a1 - idx_a2) != sign(idx_b1 - idx_b2),则记录组合.

First formulate your logic mathematically. For all combinations of length 2, given indices idx_a1, idx_a2 and idx_b1, idx_b2, if sign(idx_a1 - idx_a2) != sign(idx_b1 - idx_b2), record the combination.

下面的代码效率不高,但是显示了一种将这种逻辑转换为代码的方法:

The below isn't efficient, but it shows one way of transforming this logic to code:

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')]

这篇关于元素列表比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆