将多个值分配给变量,如果列表中有任何值匹配,则继续执行if语句



我要做的事情:

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

我知道这个代码目前是不起作用的,但这是为了帮助我理解我遇到的问题,本质上我想给vari分配多个值,如果其中一个值位于我的if语句中,那么它会选择该值并临时将i分配给它。

您没有正确使用any()——它需要是一系列条件,例如any(x in i if x in line)

any()不会告诉您列表中的哪个元素匹配。相反,您可以使用列表理解来获取所有匹配的元素,并测试它是否为空。

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

不要重用变量i,因为没有办法将其恢复到原始值。

我认为不是这样:

any(i) in line

你真的想要:

any((value in line) for value in i)

CCD_ 8对CCD_ 9的所有值进行迭代,并评估这些值中是否有任何值评估为CCD_。

因此,您创建了一个生成器,该生成器获取i中的每个值,并测试它是否在line中,如果其中任何一个值为true,则处理停止,any返回true。否则,将测试所有值,并返回False

最新更新