Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the python equivalent of the Perl pattern to track if something has already been seen?

Tags:

python

perl

In Perl, one can do the following

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

I would like to be able to do the equivalent in Python, that is to skip a block if it has been executed once.

like image 909
jnman Avatar asked Feb 03 '10 00:02

jnman


2 Answers

seen = set()
for x in foo:
    if x in seen:
        continue
    seen.add(x)
    # do something

See the set documentation for more information.

Also, the examples at the bottom of the itertools module documentation contains a unique_everseen generator that you can use like this:

for x in unique_everseen(foo):
    # do something
like image 78
Greg Hewgill Avatar answered Nov 15 '22 04:11

Greg Hewgill


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
like image 44
ghostdog74 Avatar answered Nov 15 '22 02:11

ghostdog74