0 python iteration indexing loops
试图理解为什么我的代码返回所述资本的后续实例的重复大写字母的第一个位置:
任务:返回包含给定字符串中大写索引的有序列表
我的代码:
def capitals(word):
cap = []
for i in word:
if i.isupper():
cap.append(word.index(i))
return cap
Run Code Online (Sandbox Code Playgroud)
输出:
[1, 6, 9, 12, 13, 9] 应该相等 [1, 6, 9, 12, 13, 14]
小智 5
这实际上可以简化为
capitals = lambda word: [i for i,val in enumerate(word) if val.isupper()]
Run Code Online (Sandbox Code Playgroud)
...然后它也适用于相邻的相等字母:
capitals("ThiSiSaTeSTT")
> [0, 3, 5, 7, 9, 10, 11]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
103 次 |
| 最近记录: |