Home > other >  Why are these extra 's's appearing on my concatenated list?
Why are these extra 's's appearing on my concatenated list?

Time:07-16

I am trying to make a program that generates a deck of 52 non-repeating cards. Each card has a value between 2 and 13 and is then assigned a suit. I managed to get some results, but it doesn't quite work. I just want it to look like [2s, 3s, 4s, ... 13s, 2c, 3c, ....] etc until it exhausts all four suits.

s = 0
value = list(range(2, 14))
sDeck = []
cDeck = []
hDeck = []
dDeck = []

while s <= 3:
    if s == 0:
        sDeck = [x   's' for x in str(value)]
    elif s == 1:
         cDeck = [x   'c' for x in str(value)]
    elif s == 2:
        hDeck = [x   'h' for x in str(value)]
    elif s == 3:
        dDeck = [x   'd' for x in str(value)]
    s  = 1
Deck = sDeck   cDeck   hDeck   dDeck

The results I am getting are just a mess. I imagine I have a very fundamental piece of understanding missing when it comes to writing loops.

CodePudding user response:

The problem is hidden here:

cDeck = [x   'c' for x in str(value)]

value is a list which look like

[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

when you wrap it with str() you get a string yes, but it looks like

'[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]'

So when you iterate over this string you deffinately will observe a wrong result. To fix this problem your code should be:

sDeck = [str(x)   's' for x in value]

Here you wrap with str() each separate value from range.

P.S. you also can use just value = range(2, 14) instead of value = list(range(2, 14))

CodePudding user response:

str(value) doesn't convert each of your list element to a string, use map(str, value) instead.

s = 0
value = list(range(2, 14))
sDeck = []
cDeck = []
hDeck = []
dDeck = []

while s <= 3:
    if s == 0:
        sDeck = [x   's' for x in map(str, value)]
    elif s == 1:
         cDeck = [x   'c' for x in map(str, value)]
    elif s == 2:
        hDeck = [x   'h' for x in map(str, value)]
    elif s == 3:
        dDeck = [x   'd' for x in map(str, value)]
    s  = 1
Deck = sDeck   cDeck   hDeck   dDeck

print(sDeck)
print(cDeck)
print(hDeck)
print(dDeck)

CodePudding user response:

You can nest two iterators in a list comprehension. So one simple way to get that deck would be:

deck = [ str(card) suit for suit in 'schd' for card in range(2,14) ]

Note that when you have two for clauses in a comprehension, the first one is the outer loop; the idea is that it mimics the order of iteration of an explicit loop:

for suit in 'schd':
    for card in range(2, 14):
        deck.append(str(card)   suit)

You can also write that with an "f-string":

deck = [ f"{card}{suit}" for suit in 'schd' for card in range(2,14) ]
  • Related