gpt4 book ai didi

python - 当列表索引超出范围时环绕列表

转载 作者:太空狗 更新时间:2023-10-29 19:32:58 26 4
gpt4 key购买 nike

我正在寻找一些代码改进,或者我自己实现的预构建版本,因为我认为可能或者应该有一种更简洁的方法来实现我想要的。

我正在编写一个将吉他谱转换为古典乐谱的软件,我需要将谱上的数字转换为相应的音符,这对于从起始字符串构建每个弦音符的列表很有用。

我有一个音符列表 (a - g#) 和一个品格列表 (0, 21)。

Notes[fret] 在前 11 个音符上工作正常,但在那之后我显然遇到了超出索引的错误。

我必须解决这个问题的代码在这里:

notes = ["a", "a#", "b", "c", "c#", "d", "e", "f", "f#", "g", "g#"]
note = 21
while note >= len(notes):
note -= 11
try:
print notes[note]
except:
continue

可以用,但是看起来有点长,有没有更好的方法呢?

最佳答案

使用 % operator产生模数:

notes[note % len(notes)]

演示:

>>> notes = ["a", "a#", "b", "c", "c#", "d", "e", "f", "f#", "g", "g#"]
>>> note = 21
>>> notes[note % len(notes)]
'g#'

或在循环中:

>>> for note in range(22):
... print notes[note % len(notes)],
...
a a# b c c# d e f f# g g# a a# b c c# d e f f# g g#

关于python - 当列表索引超出范围时环绕列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22122623/

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