首页 > 解决方案 > 列表中项目的重复索引

问题描述

我的索引有问题我的列表如下所示:

['Persian', 'League', 'is', 'the', 'largest', 'sport', 'event', 'dedicated', 
'to', 'the', 'deprived', 'areas', 'of', 'Iran', 'Persian', 'League', 
'promotes', 'peace', 'and', 'friendship', 'video', 'was', 'captured', 'by', 
'one', 'of', 'our', 'heroes', 'who', 'wishes', 'peace']

我希望大写名称的打印索引白色大写名称看起来像这样:

0:Persian
1:League
13:Iran
14:Persian
15:League

但我不能打印如下所示的 reapet 索引:

0:Persian 
1:League
13:Iran
0:Persian   <=======
1:League    <=======

请帮帮我!

标签: pythonpython-3.x

解决方案


您将不得不为此使用列表推导:

[(i, word) for i, word in enumerate(l) if word.istitle()]
>> [(0, 'Persian'), (1, 'League'), (13, 'Iran'), (14, 'Persian'), (15, 'League')]

该函数istitle()检查单词的第一个字母是否以大写字母开头。

或者您可以使用:

for i, word in enumerate(l):
    if word.istitle():
        print(i,': ', word)

0 :  Persian
1 :  League
13 :  Iran
14 :  Persian
15 :  League

推荐阅读