python-3.x - 有没有办法从具有递减范围的 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
?
解决方案
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())
推荐阅读
- c# - How to for loop asp:label or asp:PlaceHolder tag with select asp:checkbox any checkbox in .NET C#?
- android - 如何在 Kotlin 中使用相同的按钮隐藏和显示视图
- sap - 在后台-SAP Hyrbis 1905 中看不到运行 cronjob 按钮?
- lottie - 如何在不提供路径的情况下直接使用 JSON 内容加载 lottie-web 动画
- rust - 如何使用 actix-web 的 Json 类型解决“serde::Deserialize 的实现不够通用”?
- xamarin.forms - ZXING 手机重复扫描问题
- python - IndexError:列表索引超出创建新列表的范围
- internet-explorer - JSzip“generateAsync”不能在 Internet Explorer 上运行?
- javascript - How to handle puppeteer exception on synchronous execution
- android - Home screen like facebook