[英]Python - how to count an index of a list continuously without using libraries?
Below I have a List of the lowercase alphabet.下面我有一个小写字母列表。 My task is to get the index of a lowercase letter from the list and add the shift.
我的任务是从列表中获取小写字母的索引并添加移位。 The shift can vary and be other than 1000. It could also be 50000 or 10 etc. If the index + shift is larger than 25, it should continue counting from "a" until (index + shift) has been reached and return the letter.
shift 可以变化,不是 1000。它也可以是 50000 或 10 等。如果 index + shift 大于 25,它应该从 "a" 继续计数,直到达到 (index + shift) 并返回字母. I am not allowed to use libraries.
我不被允许使用图书馆。
My solution doesn't work for big shifts like 1000我的解决方案不适用于 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])
Result should be: 'g'结果应该是:'g'
what I get is:我得到的是:
---------------------------------------------------------------------------
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
----------------------------------------------------------------------------
You are looking for the modulo operator.您正在寻找模运算符。 From the documentation (emphasis is mine):
从文档(重点是我的):
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.
零右参数引发 ZeroDivisionError 异常。 The arguments may be floating point numbers, eg, 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);
参数可以是浮点数,例如,3.14%0.7 等于 0.34(因为 3.14 等于 4*0.7 + 0.34。) the absolute value of the result is strictly smaller than the absolute value of the second operand
结果的绝对值严格小于第二个操作数的绝对值
index = (index + shift) % len(alphaList)
在此处使用模数运算符:
index = (index+shift) % len(alphaList)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.