基于间隔列表跳过数组项

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

Skipping array items based in a list of intervals

问题

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

我想要创建音符列表:

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

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

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:

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

skip their indexes by this set of intervals:

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写的类似 -

notes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
intervals = [2, 1, 2, 2, 1, 2, 2]
idx = 3

for interval in intervals:
    print(notes[idx])
    idx += interval
    idx %= len(notes)

结果

D#
F
F#
G#
A#
B
C#
英文:

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

notes =  ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
intervals = [2, 1, 2, 2, 1, 2, 2]
idx = 3

for interval in intervals:
    print(notes[idx])
    idx += interval
    idx %= len(notes)

result

D#
F
F#
G#
A#
B
C#

答案2

得分: 0

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

notes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
intervals = [2, 1, 2, 2, 1, 2, 2]
idx = 3

for interval in intervals:
    print(notes[idx])
    idx += interval
    if idx > len(notes):
        idx -= len(notes)

输出

D#
F
F#
G#
A#
B
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.

notes =  ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
intervals = [2, 1, 2, 2, 1, 2, 2]
idx = 3


for interval in intervals:
    print(notes[idx])
    idx += interval
    if idx > len(notes):
        idx -= len(notes)

output

D#
F
F#
G#
A#
B
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:

确定