What is the python equivalent of a Perl tracking template if something has already been noticed?

In Perl, you can do the following

for (@foo) {
    # do something 
    next if $seen{$_}++;
}

I would like to be able to make an equivalent in Python, i.e. skip a block if it was executed once.

+5
source share
3 answers
seen = set()
for x in foo:
    if x in seen:
        continue
    seen.add(x)
    # do something

See the documentation for more information set.

In addition, the examples at the bottom of the itertools document contain a generator unique_everseenthat can be used as follows:

for x in unique_everseen(foo):
    # do something
+11
source
seen={}
for item in foo:
   if seen.has_key(item):
      seen[item]+=1
      continue # continue is optional, just to illustrate the "next" in Perl
   else:
      seen[item]=1
+1
source

foo, , , .

for x in set(foo):
    do something
+1

All Articles