重复列表中项目的索引

时间:2019-03-08 12:09:19

标签: python python-3.x

我的白衣指数有问题 我有一个看起来像这样的列表:

['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    <=======

请帮助我!

3 个答案:

答案 0 :(得分:3)

您必须为此使用列表理解:

[(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

答案 1 :(得分:3)

最短的理解,返回格式化的字符串:

["{}:{}".format(*x) for x in enumerate(lst) if x[1].istitle()]

答案 2 :(得分:2)

这是因为列表index()返回列表中第一次出现的索引。因此,无论列表中有多少个'Persian',都只会获取第一个'Persian'的索引。

使用enumerate遍历列表以跟踪索引,我建议创建字典,以便您可以在以下方面进一步使用它:

lst = ['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']

output = {i: x for i, x in enumerate(lst) if x.istitle()}
# {0: 'Persian', 1: 'League', 13: 'Iran', 14: 'Persian', 15: 'League'}