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.
CodePudding user response:
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.
CodePudding user response:
I think instead of this:
any(i) in line
you really want:
any((value in line) for value in i)
any(something)
iterates over all values of something
and evaluates whether any of those values evaluate to True
.
Therefore you create a generator that gets each value in i
and tests whether it's in line
and if any of them are true, processing stops and any
returns True. Otherwise all values are tested and it returns False