比较许多值并判断它们是否相等

时间:2019-08-07 11:23:55

标签: python compare comparison

我正在一个项目上,我需要相互比较一些值并判断它们是否不匹配。我有13个列表,每个列表都有500多个值。所有十三个列表具有相同的长度。我想在这13个列表中的任何一个中找到该项目的索引。

但是我试图通过列出三个列表来简化问题,每个列表包含四个项目。


list1 = [1, 2, 2, 2]
list2 = [1, 3, 2, 2]
list3 = [2, 4, 2, 2]

Blist = [list1, list2, list3]

for i in range(len(Blist)): #0, 1, 2
    for j in range(len(Blist)): #0, 1, 2
        if i == j:
            pass
        else:
            for k in range(len(list1)): #0, 1, 2, 3
                st = Blist[i][k] != Blist[j][k]
                print(st)

我可以一次比较两个列表,但是我无法提出一种解决方案,该解决方案将比较具有相同索引的所有项目并向我返回其值不匹配的索引“ ind”的值(当您比较list1 [ind],list2 [ind]和list3 [ind])。

如果我只能写三个列表

for i in range(len(list1)):
    if (list1[i] != list2[i] and list1[i] != list3[i] and list2[i] != list3[i])
        print(i)

但是我想解决一个问题,即使它具有数百个包含数百个项目的列表。

2 个答案:

答案 0 :(得分:0)

对于每个索引,创建一个set值,这些值从每个嵌套列表的单个索引中获取值。由于set不能有重复的元素,因此集合的长度应等于嵌套列表的总数。否则,将存在重复项,这意味着该索引的所有值都不都是唯一的。

values = [
    [1, 2, 2, 2, 5],
    [1, 3, 2, 2, 7],
    [2, 4, 2, 2, 1]
]

n = len(values[0])  # Number of values in each nested list
total = len(values)  # Total number of nested lists

for i in range(n):
    s = {v[i] for v in values}
    if len(s) == total:
        print(i)

输出:

1
4

如果您了解上述方法,则可以使用某种实用的方法来减少代码。基本上是2行python代码。 (多行编写以提高可读性)。

values = [
    [1, 2, 2, 2, 5],
    [1, 3, 2, 2, 7],
    [2, 4, 2, 2, 1]
]
total = len(values)

# Using a list comprehension to create a list with the unique indices
unique_indices = [
    idx 
    for idx, s in enumerate(map(set, zip(*values))) 
    if len(s) == total
]
print(unique_indices)

输出:

[1, 4]

答案 1 :(得分:-1)

如果允许您使用numpy,则

array_nd = np.array(Blist)
uniqueValues , indicesList, occurCount= numpy.unique(array_nd, return_index=True, return_counts=True)
从上面的过滤器

中,所有它们的均将count设为1的索引,您可以从indexsList获取其索引。

相关问题