我正在尝试使用带有符号的一副纸牌替换python列表。
我尝试使用Python的替换功能,但是我认为最好的解决方案可能是基于正则表达式替换。
所需的结果将是这样:
"Ah" => "A♥"
"5h" => "5♥"
等
当前列表中包含以下项: [玩家名称],[玩家钱包],[第一张玩家卡],[第二张玩家卡]
可能是:
["Don Johnson", 100, "Ks", "5d"]
["Davey Jones", 100, "4c", "3h"]
任何帮助,将不胜感激。谢谢。
(根据要求进行编辑,以供澄清-感谢您到目前为止的所有输入!)
答案 0 :(得分:2)
在这里,我们可以简单地使用四个简单的表达式并进行我们希望的替换:
([AKJQ0-9]{1,2})h
([AKJQ0-9]{1,2})d
,其他两个类似。
# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"([AKJQ0-9]{1,2})h"
test_str = ("Ah\n"
"10h")
subst = "\\1♥"
# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)
if result:
print (result)
# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
答案 1 :(得分:2)
如果您只有一张卡片列表,则可能看起来像这样:
cards = ['2h', '2s', '2c', '2d', '3h', '3s', '3c', '3d', '4h', '4s', '4c', '4d', '5h', '5s', '5c', '5d', '6h', '6s', '6c', '6d', '7h', '7s', '7c', '7d', '8h', '8s', '8c', '8d', '9h', '9s', '9c', '9d', '10h', '10s', '10c', '10d', 'Ah', 'As', 'Ac', 'Ad', 'Kh', 'Ks', 'Kc', 'Kd', 'Jh', 'Js', 'Jc', 'Jd', 'Qh', 'Qs', 'Qc', 'Qd']
如果是这样,则只需使用字典和理解即可:
suits = {'h': '♥', 's': '♠', 'c': '♣', 'd': '♦'}
new_cards = [''.join(rank)+suits[suit] for *rank, suit in cards]
输出为:
['2♥', '2♠', '2♣', '2♦', '3♥', '3♠', '3♣', '3♦', '4♥', '4♠', '4♣', '4♦', '5♥', '5♠', '5♣', '5♦', '6♥', '6♠', '6♣', '6♦', '7♥', '7♠', '7♣', '7♦', '8♥', '8♠', '8♣', '8♦', '9♥', '9♠', '9♣', '9♦', '10♥', '10♠', '10♣', '10♦', 'A♥', 'A♠', 'A♣', 'A♦', 'K♥', 'K♠', 'K♣', 'K♦', 'J♥', 'J♠', 'J♣', 'J♦', 'Q♥', 'Q♠', 'Q♣', 'Q♦']
对于您的解决方案,您可以定义一个纠正卡的功能:
def fix_card(card):
suits = {'h': '♥', 's': '♠', 'c': '♣', 'd': '♦'}
*rank, suit = card
return ''.join(rank)+suits[suit]
然后像这样使用它:
player = ["Don Johnson", 100, "Ks", "5d"]
player[2] = fix_card(player[2])
player[3] = fix_card(player[3])
print(player)
#["Don Johnson", 100, "K♣", "5♦"]
答案 2 :(得分:0)
否,像这样的简单替换不需要正则表达式。只需使用str.replace
:
>>> cards = ['Ah', '5h']
>>> [s.replace('h', '♥') for s in cards]
['A♥', '5♥']