如何在Python中的函数内的不同项目上循环列表?

harrisamam932

我刚刚开始使用Python中的函数。我的目标是循环显示带有水果的列表,并为每个水果向后打印字母。当遇到特殊字符时,它将停止并继续前进到下一个水果。我尝试使用循环来执行此操作,并每次都将其添加到索引中,但这只会正确打印第一个水果。如果我仅将每个水果的代码放置五次,则效果很好。请帮助我修复索引。代码如下。

def reverse(li):
    c = 1
    while c == 1:
        index = 0
        for c in reversed(li[index]):
            if c.isalpha():
                print(c, end="")
                index += 1
            else:
                print()
                index += 1
                break

fruits = ['ap!ple','bana@na','ma%ngo','#orange','pine*apple']
reverse(fruits)
黑雷

您仅循环浏览列表的第一个元素(reversed(li[index]))。

def reverse(li):
    for word in li:
        for rev_word in reversed(word):
            if rev_word.isalpha():
                print(rev_word, end="")
            else:
                print()
                break

fruits = ['ap!ple','bana@na','ma%ngo','#orange','pine*apple']
reverse(fruits)

输出:

elp
an
ogn
egnaro
elppa

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章