3

I'm running this code, which is supposed to remove element that meet a certain requirement from a list while iterating through it:

linkList[:] = [link for link in linkList if "some string" in (self.visitedLinkDictionary[link] == 1) and (link.split('/')[2])]

I changed the code to that after reading the answers to this question. Previous version was:

addNodes = 0
for link in linkList:
    self.visitedLinkDictionary[link] += 1
    #control that the link has not been checked previously
    if self.visitedLinkDictionary[link] == 1:
        #control that the link belongs to the caltech domain
        checkDomain = link.split('/')
        if "some string" in checkDomain[2]:
            addedNodes += 1
        else:
            print "Not in 'some string' domain"
            del linkList[i]
    else:
        print "Duplicated hyperlink"
        del linkList[i]
    i += 1

print addedNodes

What I'm trying to do is go through a list of strings and check if two conditions are met:

  • First a given string should not be contained in the self.visitedLinkDictionary
  • Secondly it should contain the substring 'some string'

Can anybody please tell me what I'm doing wrong in any/both of cases and eventual better ways to implement this code?

Community
  • 1
  • 1
Matteo
  • 7,924
  • 24
  • 84
  • 129

1 Answers1

3

The result of the comparison self.visitedLinkDictionary[link] == 1 is a boolean (True or False). And then you try to iterate over that using in which generates a TypeError since booleans are not iterable.

You want instead:

linkList[:] = [link for link in linkList 
               if self.visitedLinkDictionary[link] == 1 and 
                  "some string" in link.split('/')[2]]
mechanical_meat
  • 163,903
  • 24
  • 228
  • 223