Home > front end >  Comparing a list element with all others list's elements in search for equal values
Comparing a list element with all others list's elements in search for equal values

Time:06-24

I have a LIST with 240 time series. two pairs in that list are EQUAL, let's suppose list[4] is equal to list[36] and list[105] is equal to list[208] let's also suppose I don't know that these pairs are equal. How can I check it in my code?

if I do list[4] == list[36] it'll return a series with True values and that's the only way I can think of verifying this. So I guess I'll have to do something like: list[1] == list[ i ] (all lists expect list[1]) and if it finds a TRUE value, it'll mark them as equal, them list[2] == list[i] (except list[2]), and so on

CodePudding user response:

This will give you a list of lists, the values being the indices of matching lists:

_LIST = [[1, 2], [3, 4], [5, 6], [1, 2], ['a', 'b'], ['c', 'd'], [5, 6]]

res = []
for i, v in enumerate(_LIST):
    idxs = [idx   i for idx, val in enumerate(_LIST[i:]) if v == val]
    if len(idxs) > 1:
        res.append(idxs)

print(res)
[[0, 3], [2, 6]]

Alternatively, you can use the .index() method like so:

_LIST = [[1, 2], [3, 4], [5, 6], [1, 2], ['a', 'b'], ['c', 'd'], [5, 6]]

res = []
for i, v in enumerate(_LIST):
    try:
        dup_idx = _LIST[i 1:].index(v)   i   1
        res.append([i, dup_idx])
    except ValueError: # pass up unique lists, throws ValueError because dup_idx doesn't exist
        pass

print(res)
[[0, 3], [2, 6]]
  • Related