首页 > 解决方案 > 有没有办法从具有递减范围的 Python 'for' 循环中获取递增计数器?

问题描述

我读到每个人都使用枚举,但我认为我不知道如何在我的代码中使用它。我想根据字母顺序打印字符串中字母的值,下一个字符将值增加 1,我想从字符串中的最后一个字符开始。

我可以解决代码,但是如何在i不使用i = i+1使代码更短的情况下替换计数器?有没有办法在for循环中实现某些东西?

这是我的代码:

    def project(r):
       i = 0
       for char in range(len(r),0,-1):
          print(ord(r[char-1])-96+i)
          i=i+1

    project(str(input()).lower())

例如,如果我插入一个字符串,例如"sad",输出将是[4,2,21]因为d = 4, a = 1, s = 19

有没有办法在不初始化的情况下实现计数器i

标签: python-3.xfor-loop

解决方案


If you want to make it shorter, you can use the decrement char value since we can get an increment by subtracting the length of the string (input) with char in the for loop.

For example, this is my code:

    def project(r):
        for char in range(len(r),0,-1):
            print(ord(r[char-1])-96+(len(r)-char))
    project(str(input()).lower())

推荐阅读