列表索引超出范围时环绕列表

时间:2014-03-02 01:11:04

标签: python list

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

我正在编写一个软件来将吉他标签转换为经典表示法,我需要将标签上的数字转换为相应的音符,这对于从起始字符串构建每个字符串音符的列表非常有用。

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

注释[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

它有效,但看起来有点长,有更好的方法吗?

3 个答案:

答案 0 :(得分:20)

使用% 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#

答案 1 :(得分:2)

使用模运算符:

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'

答案 2 :(得分: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]