我正在嘗試做的事情:
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
我知道這段代碼目前不起作用,但這是幫助我理解我遇到的問題的方式,本質上我想為 var 分配多個值i
,如果其中一個值位于我的if
陳述句中,那么它會選擇該值并暫時分配i
給它。
uj5u.com熱心網友回復:
您沒有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
,因為無法將其恢復為原始值。
uj5u.com熱心網友回復:
我認為不是這樣:
any(i) in line
你真的想要:
any((value in line) for value in i)
any(something)
遍歷 的所有值something
并評估這些值中的任何一個是否評估為True
.
因此,您創建了一個生成器,它獲取每個值i
并測驗它是否在line
其中,如果其中任何一個為真,則處理停止并any
回傳 True。否則測驗所有值并回傳False
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/507188.html