当列表索引超出范围时,列表回绕
- 2025-03-21 09:06:00
- admin 原创
- 34
问题描述:
我正在寻找一些代码改进,或者我自己实现的预构建版本,因为我认为可能有或应该有一种更清晰的方法来实现我想要的。
我正在编写一个软件,将吉他谱转换成古典乐谱,我需要将谱表上的数字转换为其对应的音符,这对于从起始弦开始构建每个弦音符的列表很有用。
我有一个音符列表(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
它有效但是似乎有点长,有没有更好的方法来做到这一点?
解决方案 1:
使用%
运算符生成模数:
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#
解决方案 2:
另一个选择是使用itertools.cycle
>>> import itertools
>>> notes = ["a", "a#", "b", "c", "c#", "d", "e", "f", "f#", "g", "g#"]
>>> frets = range(21)
>>> for note, fret in itertools.izip(itertools.cycle(notes), frets):
print ("[%s, %d]" %(note, fret))
[a, 0]
[a#, 1]
[b, 2]
[c, 3]
[c#, 4]
[d, 5]
[e, 6]
[f, 7]
[f#, 8]
[g, 9]
[g#, 10]
[a, 11]
[a#, 12]
[b, 13]
[c, 14]
[c#, 15]
[d, 16]
[e, 17]
[f, 18]
[f#, 19]
[g, 20]
解决方案 3:
使用模运算符:
In [3]: notes = ["a", "a#", "b", "c", "c#", "d", "e", "f", "f#", "g", "g#"]
In [4]: len(notes)
Out[4]: 11
In [5]: note = 11
In [6]: notes[note]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-6-707e7e351463> in <module>()
----> 1 notes[note]
IndexError: list index out of range
In [7]: notes[note%len(notes)]
Out[7]: 'a'
In [8]: notes[note-11]
Out[8]: 'a'
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD