如何在屏幕上获取枚举对象?

问题描述 投票:-1回答:1

我想用word="WElCMMerC "来书写屏幕上的大写字母和索引号,例如[(0,W),(1,E),(3,C),(4,M),(5,M)...]。


def cap(word):

    w=list(enumerate(i) for i in word if i!=i.lower())
    print (w)

print(cap("WElCMMerC"))
python uppercase enumerate
1个回答
2
投票

你可以循环处理 enumerate,只保留有大写字母的部分(用 isupper 来检查),并返回列表中的 w,不要在函数内部打印。

def cap(word):
    w = [i for i in enumerate(word) if i[1].isupper()]
    return w

print(cap("WElCMMerC"))

输出:

[(0, 'W'), (1, 'E'), (3, 'C'), (4, 'M'), (5, 'M'), (8, 'C')]

0
投票

你做了一个列表 enumerate 对象。 阅读文档。enumerate 是一个迭代器,很像 range. 相反,你需要 使用 的列举。

return [(idx, letter) 
        for idx, letter in enumerate(word)
            if letter.isupper()]

在英文中:

Return the pair of index and letter
for each index, letter pair in the word
    but only when the letter is upper-case.
© www.soinside.com 2019 - 2024. All rights reserved.