python - 列表中项目的重复索引
问题描述
我的索引有问题我的列表如下所示:
['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
推荐阅读
- java - 更新和删除在 Spring Boot 应用程序上不起作用
- c++ - 是否可以在运行时强制转换模板参数?
- excel - 检查 Word 实例是否正在运行
- git - Git 无法识别/列出我的仓库的分支
- c++ - 为自己的类和 std::string 重载 + 运算符
- python - python请求通用异常处理
- javascript - 当我尝试提交 HTML 表单时显示错误“无法 POST”
- amazon-web-services - API 网关集成中使用代理集成有什么用?
- c - openssl 会话票证 - 仅使用 enc=1 调用 SSL_CTX_set_tlsext_ticket_key_cb 回调
- matlab - 如何在MATLAB中获得一些图像的并集?