开发者

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

开发者 https://www.devze.com 2022-12-19 03:48 出处:网络
In Perl, one can do the following 开发者_开发问答for (@foo) { # do something next if $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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号