一首诗 wrote:
Hi all,Today I wrote some code like this: for m in self.messages: if not m.finished: continue #process the message fini = [m for m in self.messages if m.finished] for m in fini: self.messages.remove(m) As you can, I want to find these finished messages in "self.messages", process them, and then remove them from the list. Because a list can not be modified while iterating it, I have to use a list "fini" to accomplish the target. I found a smell of bad performance here. Is there any faster ways?
I'm not getting what your code really wants to do - you are iterating over messages, and if its "not" finished, skip over it and process all which are finished. (If they are finished, why process them?) Wouln't it make more sense to call the process where you process the messages? And you could just pop() the list or use some of the queue implementations for better performance. e.g. def enqueue_messages(self,msg): self.messages.append(msg) def process_messages(self): if self.messages: msg=self.messages.pop(0) process(msg) if you want some post processing, its really like you are acting in different stages, so you could just have two lists for your messages: one for the messages in phase1, one for the messages passed phase1 and now in phase2 and work over them in the way shown above. Regards Tino
-- http://mail.python.org/mailman/listinfo/python-list
smime.p7s
Description: S/MIME Cryptographic Signature
-- http://mail.python.org/mailman/listinfo/python-list