我有一个索引的问题,我有一个列表,看起来像这样:
['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 <=======请帮帮我!
发布于 2019-03-08 20:13:52
为此,您必须使用列表理解:
[(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发布于 2019-03-08 20:18:23
返回格式化字符串的最短理解:
["{}:{}".format(*x) for x in enumerate(lst) if x[1].istitle()]https://stackoverflow.com/questions/55062957
复制相似问题