1

I want to create a deck of cards by combining a list containing card values:

[7,8,9,10,J,Q,K,A] 

and a list containing colors:

[♣,♥,♠,♢]

to get all combinations once.

Is there some simple way to combine lists (or strings) in this way?

I tried several ways but none worked (maybe because special characters used directly (♣,♥,♠,♢) and not in the \N{xxxxx} way? )

expected outcome would be list/dictionary containing all possible combinations exactly once:

["7♣","7♥","7♠","7♢","8♣","8♥","8♠","8♢", ....."A♣","A♥","A♠","A♢"]

thanks alot for helping guys :)

Ahmad F
  • 30,560
  • 17
  • 97
  • 143
  • 2
    A for loop to iterate over ranks, another for loop to iterate over suits, nested inside the first loop. Print the current combination of rank + suit. Presto! – John Gordon Sep 08 '19 at 16:20
  • 2
    Is the difficulty with an algorithm to generate the combinations or the special characters for the card suits? This will shape the answer. – paisanco Sep 08 '19 at 16:22
  • The main problem is to create combination. "secondary question would be if i can use directly those four special characters or if i need to use \N{something} for them" – Martin Kočka Sep 08 '19 at 16:25

3 Answers3

3

You want a Cartesian product. The itertools.product function does this, but you can also use two for loops.

[rank+suit for rank in ['7','8','9','10','J','Q','K','A'] for suit in '♣♥♠♢']

or

from itertools import product

[rank+suit for rank, suit in product(['7','8','9','10','J','Q','K','A'], '♣♥♠♢')]
gilch
  • 10,813
  • 1
  • 23
  • 28
1

A simple nested list-comprehension will do the trick:

nums = ['7','8','9','10','J','Q','K','A']
colors = ['♣','♥','♠','♢']

res = [num+color for num in nums for color in colors]

This gives:

['7♣', '7♥', '7♠', '7♢', '8♣', '8♥', '8♠', ..., 'K♥', 'K♠', 'K♢', 'A♣', 'A♥', 'A♠', 'A♢']

*output truncated

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
0

Use itertools.product:

>>> ranks = ["7", "8", "9", "10", "J", "Q", "K", "A"]
>>> suits = ["♣","♥","♠","♢"]
>>> [''.join(x) for x in product(ranks, suits)]
['7♣', '7♥', '7♠', '7♢', '8♣', '8♥', '8♠', '8♢', '9♣', '9♥', '9♠', '9♢', '10♣', '10♥', '10♠', '10♢', 'J♣', 'J♥', 'J♠', 'J♢', 'Q♣', 'Q♥', 'Q♠', 'Q♢', 'K♣', 'K♥', 'K♠', 'K♢', 'A♣', 'A♥', 'A♠', 'A♢']
chepner
  • 497,756
  • 71
  • 530
  • 681