你需要轉換成int,字符串"134"
不等於整數134
:
if int(each.split('.')[0]) in firstNode:
或存儲的字符串列表:
firstNode =["134", "135"]
,如果你想找到,如果any匹配,你創建firstNode,你可以使用str.startswith這可以採取一個子串的元組來嘗試和匹配,如果我們在eac之後添加.
^h元素,我們會得到確切的匹配:
USAdetail =['134.250.7.8', '1.39.35.138', '100.43.90.10','101.43.90.10', '101.43.90.11']
firstNode = ("134.", "135.")
if any(x.startswith(firstNode) for x in USAdetail):
print("Successful")
或將它們存儲爲一個set字符串和使用in
:
USAdetail =['134.250.7.8', '1.39.35.138', '100.43.90.10','101.43.90.10', '101.43.90.11']
firstNode = {"134", "135"}
if any(x.split(".",1)[0] in firstNode for x in USAdetail):
print("Successful")
如果不控制firstnode的創作,你能堅持到鑄造爲int和從firstnode制定一套:
USAdetail =['134.250.7.8', '1.39.35.138', '100.43.90.10','101.43.90.10', '101.43.90.11']
firstNode = [134, 135]
st = set(firstNode)
if any(int(x.split(".",1)[0]) in st for x in USAdetail):
print("Successful")
any
將在第一場比賽短路,如果沒有匹配它會返回False,集合L ookups是O(1)
因此對於大量的數據將是一個非常有效的解決方案。
thx爲徹底的答案! –