What is the python equivalent of the Perl pattern to track if something has already been seen?
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.
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
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
If you don't care about the order of the things in foo, and only that the unique items are iterated over, then the solution is much simpler.
for x in set(foo):
do something
精彩评论