如何在列表中找到特定字符?

2024-10-02 16:25:43 发布

您现在位置: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")

Tags: of代码列表字符jackfivesixqueen
3条回答

请尝试以下操作

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

试试这个:

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")

你可以使用:

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

或者如果你只是想知道甲板上有没有10个:

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

相关问题 更多 >