gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 02:30:46 24 4
gpt4 key购买 nike

下面我有一个小写字母列表。我的任务是从列表中获取小写字母的索引并添加移位。 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com