Juma
Juma

Reputation: 11

How do I check whether a variable was changed?

Say I have two lists

[['1', '2', '1', '3', '1', '3'], ['A', 'G', 'T', 'T', 'T', 'G']]

In this case each index matches the number on the left with the letter on the right, so 1 : A, and 2 : G and so on. I want to see if AT LEAST one number on the left changes mapping. So, I want to know if ANY number changes mapping. So if 1 : A changes to 1 : T, I would have True returned.

Upvotes: 0

Views: 70

Answers (3)

Krzysztof
Krzysztof

Reputation: 19

If you want to know if it's not only changed but what changed this (stolen from above) should help

>>> numbers = ['1', '2', '1', '3', '1', '3']
>>> letters = ['A', 'G', 'T', 'T', 'T', 'G']

>>> def check_overwrite(keys, values):
...     d = {}
...     overlap = {}
...     for k,v in zip(keys, values):
...         if d.setdefault(k, v) != v:
...             overlap[k] = v
...     return overlap
...
>>> check_overwrite(numbers, letters)
{'1': 'T', '3': 'G'}

Upvotes: 0

Matteo Italia
Matteo Italia

Reputation: 126787

Actually perform the assignments in a dictionary, stop whenever one changes an existing entry.

def check_overwrite(keys, values):
    d = {}
    for k,v in zip(keys, values):
        if d.setdefault(k, v) != v:
            return True
    return False

print check_overwrite(['1', '2', '1', '3', '1', '3'], ['A', 'G', 'T', 'T', 'T', 'G']) 

Upvotes: 0

Ajax1234
Ajax1234

Reputation: 71451

You can create a dictionary:

s = [['1', '2', '1', '3', '1', '3'], ['A', 'G', 'T', 'T', 'T', 'G']]
new_s = {b:a for a, b in zip(*s)}
final_vals = [a for a, b in new_s.items() if any(d == b for c, d in new_s.items() if c != a)]

Output:

['A', 'T']

Upvotes: 2

Related Questions