简体   繁体   English

确定字符串的一部分是否在列表中

[英]Determining if a Part of a string is in a List

Given the input 给定输入

Guess='1 5K'

and a list 和一个清单

playable=['AC','QS','5S','5K','KC']

How would I go about determining if the '5K' part of Guess is in playable? 我如何确定Guess的“ 5K”部分是否可以播放? Also, if it is in playable, how would I go about determining if the item 1 spot to the left of it has either a '5' or a 'K' in it. 另外,如果它处于可播放状态,那么我将如何确定它左边的项目1点中是否有“ 5”或“ K”。 So playable would become 所以可玩性会变成

playable=['AC','QS','5K','KC']

With '5K' replacing '5S'. 用“ 5K”代替“ 5S”。 So far I have 到目前为止,我有

def oneC(Guess):
    split_em=Guess.split() ##splits at space
    card_guess=split_em[1] ##gets the '5K' part of string
    if card_guess is in playable:
                                          ##Confusion Area
        index1=playable.index(card_guess) ##Finds index of '5K'
        index_delete= del playable[index1-1] ##Deletes item to the left of '5K'

My problem right now is i'm not sure how to determine if '5' or 'K' is in the item one spot to the left. 我现在的问题是我不确定如何确定项目左侧的第一个点是“ 5”还是“ K”。 Is there a way to turn '5K' into a set of ('5','K') and then turn the element one spot to the left to ('5','S') and run intersection on them? 有没有办法将“ 5K”变成一组(“ 5”,“ K”),然后将元素向左一个点移到(“ 5”,“ S”)并对其进行交点? I wrote this on my phone because my internet is down at my house so sorry for any confusion or misspellings. 我之所以在手机上写这封信,是因为我的互联网不在我家门口,对于任何混乱或拼写错误,我们深表歉意。 Thanks for your time! 谢谢你的时间!

You can iterate over the characters in the item to the left and see if '5' or 'K' is in there: 您可以遍历左侧项目中的字符,并查看其中是否包含“ 5”或“ K”:

index1 = playable.index(card_guess)
if any(c in playable[index1 - 1] for c in card_guess):
    del playable[index1]

Note that the above code does not check for the case where index1 == 0 so you'd have to define what happens when the guessed card is the first card in the list. 请注意,上面的代码不会检查index1 == 0的情况,因此您必须定义当猜到的卡是列表中的第一张卡时发生的情况。

So to answer your question: for c in card_guess iterates over the characters in "5K" (which are '5' and 'K' and it then checks if any of those are in playable[index1 - 1] , which is the item to the left of "5K" ). 因此,请回答您的问题: for c in card_guess迭代"5K"的字符( '5''K' ,然后检查其中是否有任何一个在playable[index1 - 1] ,这是"5K"的左侧)。

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

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