重复列表中项目的索引

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


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

请帮帮我伙计们!


紫衣仙女
浏览 141回答 3
3回答

侃侃尔雅

返回格式化字符串的最短理解:["{}:{}".format(*x)&nbsp;for&nbsp;x&nbsp;in&nbsp;enumerate(lst)&nbsp;if&nbsp;x[1].istitle()]

牛魔王的故事

这是因为列表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'}

FFIVE

为此,您必须使用列表理解:[(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):&nbsp; &nbsp; if word.istitle():&nbsp; &nbsp; &nbsp; &nbsp; print(i,': ', word)0 :&nbsp; Persian1 :&nbsp; League13 :&nbsp; Iran14 :&nbsp; Persian15 :&nbsp; League
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python