Python transfer an object between lists

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Stefaan Ghysels
    New Member
    • Nov 2011
    • 3

    Python transfer an object between lists

    I have several lists (deck, hand, playfield, discardpile) filled with Card objects. How can I move Cards from one list to the other in a clean pythonic way ?

    This is what i have now: (and it doesn't work properly)
    Code:
    for i in range( len(hand)-1,0,-1):
      if hand[i].isRed():
        playfield.append(hand.pop(i))
    Can I do this in a smoother way ?

    Since the previous code was not doing what I want, i use this now :
    Code:
    i = 0
    while i<len(hand):
        if hand[i].isRed() :
            playfield.append(hand.pop(i))
        else : 
            i+=1
    Is this the shortest way?
  • Glenton
    Recognized Expert Contributor
    • Nov 2008
    • 391

    #2
    This looks rather efficient to me (using the append, pop methods).

    You could consider putting this into object methods instead, or creating a hand object which has an iterator, or including some of the details about which hand a card is in into the logic of the card objects themselves. Depends what you're trying to achieve really!

    Comment

    • Stefaan Ghysels
      New Member
      • Nov 2011
      • 3

      #3
      Thanks for your reply! I had troubles with iterating over a list while removing a few objects ... maybe there is a better data-structure that has ordered elements and allows selecting (and deleting) objects according to an attribute like card color ?

      Comment

      • Glenton
        Recognized Expert Contributor
        • Nov 2008
        • 391

        #4
        Interesting. It's quite a common problem, and both your ways of solving it are also quite common I believe. One thing you can't do (and which you've wisely avoided) is to iterate on the list that you're changing.

        Another approach is to use a numpy array with a mask, ie to vectorise it. This means you're dealing with the whole array at the time. So you might be able to get something like this:
        Code:
        playfield.append(hand[hand.color=="Red"])
        and skip the entire loop process.

        Or, as I said, maybe the playfield and hands can be made a property of the the card object, so you get something like this:
        Code:
        for c in card:
            if c.color=="Red" and c.location=="hand":
                c.location="playfield"
        But that's a completely different way of structuring your code, so I have no idea whether it's easier or not!

        But it looks like you're doing fine!

        Comment

        Working...