Python - 如何在不使用库的情况下连续计算列表的索引?

标签 python

下面我有一个小写字母列表。我的任务是从列表中获取小写字母的索引并添加移位。 shift 可以变化并且不是 1000。它也可以是 50000 或 10 等。如果索引 + shift 大于 25,它应该从“a”继续计数直到达到(index + shift)并返回字母.我不允许使用图书馆。

我的解决方案不适用于像 1000 这样的大类次

shift = 1000
alphaList = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

index = alphaList.index('u')
index = (index + shift) - len(alphaList)   # this part has to be adjusted 
print(index)
print(alphaList[index])

结果应该是:'g'

我得到的是:

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-20-8d37e597ee25> in <module>
      5 index = (index + shift) - len(alphaList)
      6 print(index)
----> 7 print(alphaList[index])

IndexError: list index out of range
----------------------------------------------------------------------------

最佳答案

您正在寻找模运算符。来自documentation (重点是我的):

The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand

index = (index + shift) % len(alphaList) 

关于Python - 如何在不使用库的情况下连续计算列表的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64330684/

相关文章:

python - 在 Python 中读/写文件

python - 使用关键字参数调用任务 block

python - 如何在 Tkinter 中正确设置 Canvas 大小?

python - 如何在程序生命周期内只运行一次Python方法?

Python dict.get 返回 0 评估为 false

python - 将 x 行子进程标准输出写入文件

python - Django 模型中域名的正则表达式匹配

python - 为什么 Python 在 print() 输出之前将异常打印到控制台

python - 使用 gridspec 在 A4 上绘制绘图和图像

python - 使用 PyAV 创建的视频长度