开发者

Pythonic way of doing 'for these except myself'

开发者 https://www.devze.com 2023-01-29 06:29 出处:网络
Basically, wondering what the best / most python-y way of doing this is; class thing(collectionclass):

Basically, wondering what the best / most python-y way of doing this is;

class thing(collectionclass):
    for onething in super(collectionclass,listofthings):
        if onething != self:
            do something

This is obviously a very contrived example but hopefully the point is 开发者_C百科clear!

I was thinking of folding the whole thing up into a list comprehensions but wanted to communities opinion


Please, read PEP8. I would go verbose instead of clever.

class MyThing():
    def do_something_to_everyone_but_me(self, list_of_things)
        for one_thing in list_of_things:
            if one_thing is self:
                continue
            do_something_with(one_thing)


Personally I'd use

for onething in listofthings:
    if onething is self:
        continue
    # ...

to avoid one level of nesting. You could also use a generator expression:

for onething in (x for x in listofthings if x is not self):
    # ...

Also, S.Lott's comment.

Edit: Changed == to is as per @greggo's comment. Better not get object identity and equality confused!


I say that the answer depends on the complexity of the do something. If it's simple, a list comprehension or a generator would be quite neat; if it's complex, what you have is nice and clear (if just a little verbose.)


Either continue on self, or use a genex to exclude in the first place.

for onething in (x for x in listofthings if x != self):
  ...
0

精彩评论

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