thatoneguy thatoneguy - 12 days ago 5x
Python Question

How do I put a string in a list at every nth index?

I'm working on a function that gets the suit and value as a string in a list from another function:

def getCard(n):
deckListSuit = []
grabSuit = getSuit(n)
n = (n-1) % 13 + 1
if n == 1:
return deckListSuit + grabSuit
if 2 <= n <= 10:
return deckListSuit + grabSuit
if n == 11:
return deckListSuit + grabSuit
if n == 12:
return deckListSuit + grabSuit
if n == 13:
return deckListSuit + grabSuit

With the new function it is to take the information from the above function and return it in a list with a certain structure "VALUE of SUIT".

So say if you had "3", "Spades" it would return "3 of Spades" instead.

This is my code so far on the new function.

def getHand(myList):
hand = []
for n in myList:
hand += getCard(n)
return [(" of ".join(hand[:2]))] + [(" of ".join(hand[2:4]))] + [(" of ".join(hand[4:6]))] + [(" of ".join(hand[6:8]))] + [(" of ".join(hand[8:10]))]

My question is, is how do I insert "of" between the value and suit without having to do .join a million times?


You can do it in your for loop

for n in myList:
    hand += [" of ".join(getCard(n))]

return hand

You can also do it in getCard and return '3 of Spades'

BTW: you could keep it as tuples on list

hand = [ ("3", "Spades"), ("Queen", "Spades"), ... ]

then you can use for loop instead of slices [:2], [2:4]

new_list = []
for card in hand: 
    # in `card` you have ("3", "Spades")
    new_list.append(' of '.join(card))

return new_list