简体   繁体   中英

Python: Best way to parse the following

I have a string of poker hands that looks like this:

AA:1,KK:1,AK:1,AQ:0.5,AJs:1,ATs:1,...

The number after the hand represents the weight from 0-100%. I then convert this into a dictionary that I can read the weight of the hand. The problem is the data I get lumps AKs and AKo into just AK if both hands are at the same weight. So I need some way to turn AK:1 into AKs:1 and AKo:1 and get rid of the AK:1

right now I have code that just deals with the hands and not the weights:

def parse_preflop_hand(hand):
if len(hand) < 3 and hand[0] != hand[1]:  #this avoids pairs like AA and hands like AKs
    new_hand = hand + 's' + ', ' + hand + 'o'
else:
    new_hand = hand
return new_hand

This turns AK into AKs, AKo but when I append it to a list it gets added as one item not two separate items. It also leaves the original hand in the list.

  1. How do I split this into two separate items when appending to a list?
  2. Whats most efficient way to get rid of the original hand?
  3. I import the information from a text or csv file, will converting it into a list or dictionary right away make things easier? Any other ideas appreciated.

Are you using Python3? The most minimal change to make that work is probably:

def parse_preflop_hand(hand):
    if len(hand) < 3 and hand[0] != hand[1]:
        parsed_hand = [hand + 's', hand + 'o']
    else:
        parsed_hand = [hand]
    yield from parsed_hand

Then in your main code you'll do something like:

for parsed_hand in parse_preflop_hand(unparsed_hand):
    ...

The whole code to me is probably:

# note this is different from the minimal change above
def parse_preflop_hand(hand, value):
    if len(hand) < 3 and hand[0] != hand[1]:
        return {hand + 's': value, hand+'o': value}
    else:
        return {hand: value}

final_dict = {}
for token in handstring.split(','):
    for unparsed_hand, value in token.split(":"):
        final_dict.update(parse_preflop_hand(unparsed_hand))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM