如何在列表中找到某些字符?

时间:2017-03-05 22:08:11

标签: python

我有一个列表,我想在其中找到某些字符。

playerdeck = ['Ten of Clubs', 'Six of Diamonds', 'Five of Hearts', 'Jack of Spades', 'Five of Diamonds', 'Queen of Clubs', 'Seven of Diamonds'] 

我尝试过使用此代码,但它无法正常工作:

if "Ten" in playerdeck[0:6]:
    print("y")

3 个答案:

答案 0 :(得分:0)

试试这个:

playerdeck = ['Ten of Clubs', 'Six of Diamonds', 'Five of Hearts', 'Jack of Spades', 'Five of Diamonds', 'Queen of Clubs', 'Seven of Diamonds'] 

s="Ten"
for i in playerdeck:
      if s in i:
           print(i)
           print("Found")

答案 1 :(得分:0)

请尝试以下操作。

playerdeck = ['Ten of Clubs','Six of Diamonds','Five of Hearts', \
 'Jack of Spades','Five of Diamonds','Queen of Clubs','Seven of Diamonds']
for i,item in enumerate(playerdeck):
    if 'Ten' in item:
        print('Yes:',i,item)

结果

Yes: 0 Ten of Clubs

答案 2 :(得分:0)

你可以使用:

>>> [card for card in playerdeck if 'Ten' in card]
['Ten of Clubs']

或者如果你只是想知道牌组中是否有十个:

>>> any(card for card in playerdeck if 'Ten' in card)
True