簡體   English   中英

當列表索引超出范圍時環繞列表

[英]Wrapping around on a list when list index is out of range

我正在尋找一些代碼改進,或者我自己實現的預構建版本,因為我認為可能或應該有一種更清晰的方式來實現我想要的。

我正在編寫一個軟件來將吉他譜轉換為古典記譜法,我需要將標簽上的數字轉換為相應的音符,這對於從起始字符串構建每個字符串音符的列表非常有用。

我有一個音符列表 (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

它有效,但似乎有點長,有沒有更好的方法來做到這一點?

使用%運算符生成模數:

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#

另一種選擇是使用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]

使用模運算符:

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'

這種方法適用於我的問題,但不完全適用。

我正在學習一門需要創建 Ceasar 密碼的課程。 我嘗試實施此解決方案,但在一種情況下失敗。

假設我選擇“z”作為字母並將移位設置為 1。預期輸出將是“a”,但我得到了超出范圍的錯誤。

但是,如果我選擇“z”作為字母並將移位設置為 2,則會得到正確的輸出“b”。

我真的不明白為什么會這樣,所以我很想知道。 課程中問題的實際解決方案只是復制字母表,我覺得這有點奇怪。 代碼如下。

alphabet = ['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']

direction = input("Type 'encode' to encrypt, type 'decode' to decrypt:\n")
text = input("Type your message:\n").lower()
shift = int(input("Type the shift number:\n"))

def encrypt(text, shift):


  endstring = ''
  alphabet_length = len(alphabet)

  for letter in text:
    shifted_letters = alphabet.index(letter) + shift
    if shifted_letters > len(alphabet):
      print("OUT OF RANGE!")
      print(alphabet[shifted_letters % alphabet_length])
    else:
     endstring += ''.join(alphabet[shifted_letters])

  print(endstring)

encrypt(text, shift)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM