Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Assign multiple values to variable and proceed with if statement if any of the values matched in list

What I am trying to do:

i = ["FA 3B 65 01", "DA 1C 24 71", "BA 5B 71 21"]

# hexfile = "01 FA 3B 65 01 A2 D2 F1 B3 45 21 C5 C3 BA 5B 71 21 C3 F2 34..."
with open('hexfile', 'r') as file:
   while line := file.read(32):
      if any(i) in line                   #Find "FA 3B 65 01" in first 32bytes
         any(i) = i                       #Assigns "i" to it
            # Do things with i... 
         i = i                            #Reset the value of "i" to original

I know this code is non functional currently but this is this way to help me understand the issue I am having, essentially I want to assign multiple values to var i and if one of those value is located in my if statement then it selects that value and temporarily assigns i to it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You’re not using any() correctly — it needs to be a sequence of conditions, e.g. any(x in i if x in line).

But any() won’t tell you which element of the list matched. Instead, you can use a list comprehension to get all the matching elements and test whether this is not empty.

with open('hexfile', 'r') as file:
    while line := file.read(32):
        matches = [x in i if x in line]
        if matches:
            match = matches[0] # assuming there's never more than one match
            # do things with match

Don’t reuse the variable i, since there’s no way to restore it to the original value.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading