基于间隔列表跳过数组项

huangapple go评论96阅读模式
英文:

Skipping array items based in a list of intervals

问题

所以我正在尝试使用Python编写一个程序,以自动获取给定音阶中的所有音符。

我想要创建音符列表:

  1. notes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']

然后按照以下间隔跳过它们的索引:

  1. intervals = [2, 1, 2, 2, 1, 2, 2]

提前谢谢!
我尝试手动完成它,但我真的想要自动化整个过程。

英文:

So I'm trying to code a program for my girlfriend in python to automate the process of getting all musical notes in a given scale.

I want to make the list of notes:

  1. notes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']

skip their indexes by this set of intervals:

  1. intervals = [2, 1, 2, 2, 1, 2, 2]

Thank you in advance!

I tried to do it manually but I really want to automate all the process.

答案1

得分: 1

你可以使用模运算来实现这个功能
与Edo Akse写的类似 -

  1. notes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
  2. intervals = [2, 1, 2, 2, 1, 2, 2]
  3. idx = 3
  4. for interval in intervals:
  5. print(notes[idx])
  6. idx += interval
  7. idx %= len(notes)

结果

  1. D#
  2. F
  3. F#
  4. G#
  5. A#
  6. B
  7. C#
英文:

You can use modular arithmetic for this
Similar to what Edo Akse wrote -

  1. notes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
  2. intervals = [2, 1, 2, 2, 1, 2, 2]
  3. idx = 3
  4. for interval in intervals:
  5. print(notes[idx])
  6. idx += interval
  7. idx %= len(notes)

result

  1. D#
  2. F
  3. F#
  4. G#
  5. A#
  6. B
  7. C#

答案2

得分: 0

使用一个索引来表示音符,从你想要开始的位置开始,并在循环中将每个间隔添加到索引中。如果超过列表末尾,则减去列表的长度以循环播放音符列表。

  1. notes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
  2. intervals = [2, 1, 2, 2, 1, 2, 2]
  3. idx = 3
  4. for interval in intervals:
  5. print(notes[idx])
  6. idx += interval
  7. if idx > len(notes):
  8. idx -= len(notes)

输出

  1. D#
  2. F
  3. F#
  4. G#
  5. A#
  6. B
  7. C#
英文:

use an index for the notes, start where you want, and add each interval to the index in a loop. Subtract length of the list if you're past the end to loop the notes list.

  1. notes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
  2. intervals = [2, 1, 2, 2, 1, 2, 2]
  3. idx = 3
  4. for interval in intervals:
  5. print(notes[idx])
  6. idx += interval
  7. if idx > len(notes):
  8. idx -= len(notes)

output

  1. D#
  2. F
  3. F#
  4. G#
  5. A#
  6. B
  7. C#

huangapple
  • 本文由 发表于 2023年1月9日 16:52:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75054935.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定