user1033254
user1033254

Reputation: 13

Moving items in a list a certain number of spaces

I'm trying to make a simple card game in Python.

I have to be able to move any card in my Hand list either 1 or 3 spaces to the left and if the card that is already in that spot matches either the number or suite then I need to replace it.

Here is what I've tried so far:

Assume MN is the number of spaces specified to move. Assume MC is the card specified to move that many spaces. Assume Hand is a list of the current cards in my hand.

if MN == '1':
    Hand.replace(Hand[Hand.index(MC) - int(1)], MC)
if MN == '3':
    Hand.replace(Hand[Hand.index(MC) - int(3)], MC)

So basically I gotta find out how to move the specified card (MC) the correct number of spaces (MN) in my list of cards (Hand).

If my Hand looked like this:

[ JC,  4C,  7D,  KS,  3S]

Then I should be able to move 3S 1 space to the left and have it replace KS because they have the same suite.

[ JC,  4C,  7D,  3S]

Thanks in advance for your help.

Upvotes: 0

Views: 2491

Answers (2)

Andrey Sobolev
Andrey Sobolev

Reputation: 12713

Moving an item in a list in general means popping it from its original location and inserting it to its desired location. Unfortunately, your question provides insufficient information on what your Hand and Card classes look like, but if Hand is a simple list, then the following should do:

HI = Hand.index(MC)
if (MN == '1') or (MN == '3'):
    Hand[HI - int(MN)] = MC
    Hand.pop(HI)

Note that the comparisons of the number and the suite here are omitted because of insufficient information.

Upvotes: 3

dyross
dyross

Reputation: 703

I would use the list's slice notation: http://docs.python.org/tutorial/introduction.html#lists

For example, let's say you have a list like this:

l = [1, 2, 3, 4, 5, 6, 7, 8]

And you wanted to move the element 4 over 1 space, you could do something like this:

index = 3
value = 4
spaces = 1
target = index - spaces
length = len(l)

# don't replace the element
l[0:target] + [value] + l[target:index] + l[index+1:length]
# results in [1, 2, 4, 3, 5, 6, 7, 8]

# do replace the element
l[0:target] + [value] + l[target+1:index] + l[index+1:length]
# results in [1, 2, 4, 5, 6, 7, 8]

With the parameters index, value, spaces and target extracted, this is general enough to extract into a nice function. Try it with other values (not just 1 or 3). If spaces is too high, the result will be the original list.

If you want to move the element right instead of left, you'll have to change the expression a bit, but it's the same idea.

Upvotes: 0

Related Questions