开发者

Multiple conditions inside iteration, Python

I am writing an add-on for some softwate, using its API. What i need to do is to extract necessary data. I use 'FOR' to go thought API classes. Each object has properties: index (from 0), type (Lin, Ptp, and some others), and value. Going through list of objects, I am interested in two types of objects - those that have type 'Lin' or 'Ptp'; so a few conditions should be met:

As to Lin type:

  • if there is some Ptp before Lin (there may be other obj开发者_开发技巧ects of other types between them, though), Lin gets Ptp's value [Ptp....Lin].
  • if there is some other Lin before Lin (there may be other objects of other types between them, though), Lin gets that previous closest Lin's value [Lin....Lin].
  • if there is neither Lin nor Ptp before Lin (there may be other objects of other types between them, though), Lin gets value "0" [...Lin].

As to Ptp type, it always gets its own value

As i am a beginner in Python, my thoughs are mixed now and i cannot come up with appropriate algorithm.

I was thinking it should be somthing like this:

for object in obects:
   If object.type == Ptp:
     ...object gets its own value
   elif object.type == Lin:
     ...

Here, there should be other 3 conditions according to [...Lin] or [Lin...Lin] or [Ptp...Lin]


As i am a beginner in Python, my thoughs are mixed now and i cannot come up with appropriate algorithm.

If you are trying to come up with an appropriate algorithm, take a step back. Forget Python (C++, Fortran, Logo, Awk, etc...) and think about the problem you are trying to solve. Try writing some pseudocode on paper.

From your pseudocode, the Python should become more apparent and any technical difficulties could be posed as more specific questions on StackOverflow (for instance) or asked of your colleagues.


I'd suggest you iterate over your objects, and remember the last occurrence of a Lin or Ptp type (whatever those may be ... :)):

lastOccurrence = None
for obj in objects:
    if obj.type not in ('PtP', 'Lin'):
        continue

    if obj.type == 'Lin':
        if lastOccurrence is not None:
            obj.value = lastOccurrence.value
        else:
            obj.value = "0"

    lastOccurrence = obj                

or something like that ...


I'd use something called a finite-state machine or FSM to go though the API objects. As you encounter the different types and associated properties you can store information about what was seen in the FSM's "state" which also determines what happens when the next "event" (items you are iterating over) is occurs or is encountered. Information gathered can be output as required (i.e. when a certain state is reached.

FSM's are a fairly simple concept to lean and program (in almost any language) and very useful for this sort of problem.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜