pythonfor-loopoverwrite

Python for loop overwriting


Here is my code in Python 3:

firstNode =[134, 135]
USAdetail =['134.250.7.8', '1.39.35.138', '100.43.90.10','101.43.90.10', '101.43.90.11']
for each in USAdetail:
   if each.split('.')[0] in firstNode:
       print ("successful")

I thought it should print out "successful" since there is a "134" in USAdetail. However, it seems like it is overwriting and the last element in USAdetail starts with "101", and that's why it did not print "successful".

I'm just wondering how I could change the code to make sure if there is any element in USAdetail that starts with 134/135, it would print out successful. Many thanks!


Solution

  • You need to cast to int, the string "134" is not equal to the integer 134:

    if int(each.split('.')[0]) in firstNode:
    

    Or store strings in the list:

    firstNode =["134", "135"]
    

    if you want to find if any match and you create firstNode, you can use str.startswith which can takes a tuple of substrings to try and match, if we add a . after each element we will get exact matched:

    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")
    

    Or store them as strings in a set and use 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")
    

    If you don't control firstnode creation you can stick to casting to int and make a set from 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 will short circuit on the first match, if there are no matches it will return False, set lookups are O(1) so for large amounts of data will be a very efficient solution.