在python 3.3中检查一对短语的几个值/字符串/变量

时间:2014-01-22 21:19:45

标签: python variables dictionary

我有一个包含52个键的字典:值,就像一包卡片。如果有两个或更多的值(卡片)具有相同的短语,我需要检查一个'if'语句。我需要这个函数,所以我可以多次调用它。

简而言之,我需要代码来识别“一对”牌,就像德州扑克一样,但我不希望它识别相同的值(卡)两次。 到目前为止,我已经尝试过(我不确定正确的语法,非常多的伪代码):

def cintelpair3(a, b, c, d, e):
    if any 2 'Ace' or 'Two' in(a, b, c, d, e):
        print("You have a pair")

假设变量a到e已经从字典中分配了字符串,所以将它们视为字符串;因为他们是。

3 个答案:

答案 0 :(得分:2)

我认为将5个参数放在列表中会更方便。然后,该函数适用于任何大小的手。您想要匹配的卡片可以放入列表matching_cards,该列表也适用于任何尺寸。

Python的for-else语法对于这种类型的应用程序非常有效:

def matching(hand, matching_cards):
    for card in matching_cards:
        if card not in hand:
            print("Nothing found!") # Every card needs to be in the hand
            break
    else: # Every card was found in hand, break never executed
        print("Match detected!")

如果您正在寻找精确的字符串匹配,此功能将起作用。但是,如果您想匹配手中的部分字符串(例如,您使用"Two"之类的短字来匹配"Two of Spades""Two of Hearts"等卡片,那么该功能会更高级。我认为有两种方法可以解决这个问题:

def matching(hand, matching_phrases):
    for phrase in matching_phrases:
        for card in hand:
            if phrase in card: # Phrase must be in string of at least one card
                break # Once phrase is found in one string, break
        else: # Otherwise, phrase was never found in any of the cards. No match
            print("Nothing found!")
            break
    else: # Every phrase was found in hand, break never executed
        print("Match detected!")

或者,使用更类似于@ndpu的样式。对于phrase中的每个matching_phrases,此函数会检查any的{​​{1}}是否包含card。对于要执行的phrase语句,if all必须位于其中一张卡中。

phrase

答案 1 :(得分:2)

如果函数参数是字符串,你可以这样做:

def cintelpair3(a, b, c, d, e):
    if any([a, b, c, d, e].count(card) == 2 for card in ['Ace', 'Two']):
        print("You have a pair")
对于任意数量的args,

或这种方式:

def cintelpair3(*args):
    if any(args.count(card) == 2 for card in ['Ace', 'Two']):
        print("You have a pair")

答案 2 :(得分:0)

假设您有以下词典:

your_dict = {
    'ace1': 1,
    'ace2': 1,
    ...
    'two1': 2,
    'two2': 2,
    ...
}

你可以:

import random
hand_values = {}
# Returns a list of 5 (your_dict's VALUES)
random_five = random.sample(list(your_dict.values()), 5)
for card in random_five:
    if card in hand_values:
        hand_values[card] += 1
    else:
        hand_values[card] = 1

这会产生类似的结果:

hand_values = {1: 2, 4: 2, 7: 1}

以上是说:你必须包含2张价值为1张的卡(两张Ace卡),2张价值为4张的卡(两张4张卡)和一张价值为7张的卡(一张七张卡)

然后你需要有一个dict(大概),其中包含可能的手(成对,满屋等),并按照jmu303推荐的方式做一些事情。

这当然忽略了这样一个事实:你需要比较个人的手,看谁赢了;)

相关问题