简体   繁体   English

如何检查列表中具有特定要求的所有元素?

[英]How to check all the elements in a list that has a specific requirement?

I'm doing a homework about a heart game with different version. 我正在做一个关于不同版本的心脏游戏的功课。 It says that if we are given a list mycards that contains all the cards that player currently hold in their hands. 它说如果给我们一个列表mycards ,其中包含玩家当前持有的所有牌。 And play is a single card that representing a potential card.And if all their cards contain either HEART( H ) or QUEEN OF SPADES( QS ) it is going to return True. 并且play是一张代表潜在牌的单张牌。如果所有牌都包含HEART( H )或QUEEN OF SPADES( QS ),它将返回True。

For example 例如

>>> mycards= ['0H','8H','7H','6H','AH','QS']
>>> play = ['QS']

It will return True 它将返回True

this is what I have tried 这是我试过的

if play[1] == 'H':
    return True
if play == 'QS':
    return True
else:
    return False

But I think my codes just check one QS and one H in the list. 但我认为我的代码只检查列表中的一个QS和一个H. How to make the codes that contain all either QS or H? 如何制作包含all QS或H的代码?

Your description maps directly to the solution: 您的描述直接映射到解决方案:

Edited for clarity: 编辑清晰:

mycards= ['0H','8H','7H','6H','AH','QS'] 
all((x == 'QS' or 'H' in x) for x in mycards)
#  True
>>> mycards= ['0H','8H','7H','6H','AH','QS']
>>> all(x[-1] == 'H' or x == 'QS' for x in mycards)
True

Since its your 'Homework' I'm not going to provide you with ready-made code. 由于它是您的“家庭作业”,我不打算为您提供现成的代码。 :) :)

Iterate over the list using a loop: 使用循环遍历列表:

for eg.: 例如:

for el in mycards:

at each iteration you have to check either any of the two conditions are true or not. 在每次迭代时,您必须检查两个条件中的任何一个是否为真。

if el == 'QS' or el[1] == 'H':

if card is either Queen of Spade or a Heart above condition will be true. 如果卡是锹的女王或心脏以上的情况将是真实的。 Hope you get it till now. 希望你能到现在为止。 And if the condition is not true, simply return False. 如果条件不正确,只需返回False。

If all the elements in your lists are checked by the loop and yet no False returned, hence the all cards are either Queen of Spade or a Heart. 如果循环检查了列表中的所有元素,但没有返回False,那么所有的牌都是Spade的Queen或者Heart。 So return True after the loop ends. 因此在循环结束后返回True。

Try on your own for a while, if still not getting I'll post the code at your request (but you'll have to show me what you tried :p) 试试你自己一段时间,如果仍然没有得到我会根据你的要求发布代码(但你必须告诉我你尝试了什么:p)

Edit: Since you've tried it, I'm posting code too. 编辑:既然你已经尝试过,我也会发布代码。

def HorQS(mycards):
    for i in mycards:
        if i != 'QS':
            if i[1] != 'H':
                return False
    return True

print HorQS(['0H','8H','7H','6H','AH','QS'])  # True
print HorQS(['0H','8H','7H','6H','AH','HS'])  # False
print HorQS(['0H','8H','7K','6H','AH','HS'])  # False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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