Ordering cards in Python

Asked

Viewed 327 times

1

I have a list of the cards and the suit of a deck that I need to sort. Considering the correct order: A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K And the suits: P(clubs). O(gold), E(sword), C(hearts) After reading the file with all the cards of all suits, I need to sort each suit. For example: reading the file returns (I will consider only a suit):

K P
A P
3 P 
9 P
10 P
J P
4 P
2 P
6 P
8 P
7 P
Q P
5 P

I need to sort by the value of the cards. I thought I’d play in a dictionary where the keys are the cards and the value is the suit, and then sort by the key, but I can’t get out of it. Can someone help me? My code so far:

arquivo = open('nome_arquivo.txt', 'r')
dados = arquivo.readlines()
dic = {}
for linha in dados:
    linha = linha.split()
    dic[linha[0]] = linha[1]
print(dic)
  • 1
  • If you play the cards as keys and the values being the suits, you will get (if you are working with all the cards), four cases for each key. I believe this would pose a problem for the rest of the code. nested lists the first position being the value of the card and the second value the suit.

1 answer

2


The "Sorted" method returns the sorted deck list in ascending order.

The "enumerate" method returns the index and the elements of the deck list.

Variables "k" and "v" receive the index and the list item deck.

The "strip" method removes line breaks, blank spaces, etc from the "string".

The "dic.update" method updates the dictionary, the key will be the variable "k" and "v" the value.

The "dic.get" method returns the value of a specified or empty key if the key does not exist.

arquivo = open('cartas.txt', 'r')
baralho = arquivo.readlines()

dic = {}

for k, v in enumerate(sorted(baralho)):    
    v = v.strip().strip('\n').strip('P')
    dic.update({k:v})

if dic.get(0) != 'A':
    dic.update({0:'A'})

if dic.get(9) != '10':
    dic.update({9:'10'})

if dic.get(11) != 'Q':
    dic.update({11:'Q'})

if dic.get(12) != 'K':
    dic.update({12:'K'})

print(dic)
  • 5

    Greetings from Eden. Also consider, along with the code, adding a text explanation of what you’ve implemented, how it works, and why it solves the problem in question. I saw that his last answers are basically code and this will hardly collaborate in any way for the community (and is subject to receiving negative votes). Remember that a code may be trivial to you, but not to other users.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.