python - 列表中项目的重复索引

标签 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    <=======

请大家帮帮我!

最佳答案

你将不得不为此使用列表理解:

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

关于python - 列表中项目的重复索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55062957/

相关文章:

python - 保留 BeautifulSoup 选择顺序

python - 迭代字典抛出 TypeError : list indices must be integers or slices, not tuple

python - 将按键发送到嵌入式 Pygame

django - 使用枕头处理我的 jpg 图像时出现 OSError

python - 如何使用 Boto3 按上次修改日期过滤 s3 对象

python - 读取整个文件是否会使文件句柄保持打开状态?

python - 使用 ffmpeg 和 python 将视频中的所有音频流提取到单独的音频文件中

python - 将文本转换为其行列表

python - 如何升级到最新的Anaconda 5.0.1

python - python 列表理解中的 if-else