簡體   English   中英

Python:解析以下內容的最佳方法

[英]Python: Best way to parse the following

我有一串像這樣的撲克手:

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

指針后的數字表示重量(0-100%)。 然后,我將其轉換成字典,以讀取手的重量。 問題是如果兩只手的重量相同,我會將AK和AKo混為一談。 所以我需要某種方式將AK:1轉換為AKs:1和AKo:1並擺脫AK:1

現在我有只處理雙手而不是重量的代碼:

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

這將AK轉換為AK,也就是AKo,但是當我將其追加到列表時,它將被添加為一項而不是兩個單獨的項。 它還將原始手留在列表中。

  1. 追加到列表后,如何將其分為兩個單獨的項目?
  2. 什么是擺脫原始手牌的最有效方法?
  3. 我從文本或csv文件中導入信息,是否會立即將其轉換為列表或詞典,從而使事情變得容易些? 任何其他想法表示贊賞。

您正在使用Python3嗎? 要使該工作最簡單的更改可能是:

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

然后在您的主代碼中,您將執行以下操作:

for parsed_hand in parse_preflop_hand(unparsed_hand):
    ...

給我的整個代碼可能是:

# 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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM