gpt4 book ai didi

python - 使用模式迭代列表中的项目?

转载 作者:行者123 更新时间:2023-12-01 00:38:00 26 4
gpt4 key购买 nike

我正在创建一个程序,打印出用户想要使用的音乐音阶(即 C 大调音阶)大调音阶使用半音模式,即 2 - 2 - 1 - 2 - 2 - 2 - 1

我是新人,所以不确定我的其他选择是什么。抱歉无知!

keys = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]

i = 0
while i < len(keys):
print(keys[i])
i += 2


# Output after being run:

C
D
E
F#
G#
A#

# Expected output
C
D
E
F
G
A
B

如果解释不当,我深表歉意。

最佳答案

这里现有的答案基本上是正确的,但仅适用于 C 调。如果您以任何其他注释开始,您的代码将失败并显示:

IndexError: list index out of range

这是因为从 D 开始并遵循增量模式,您最终会从 keys 数组的末尾掉下来。解决此问题的一种方法是将 keys 数组附加到自身,如下所示:

selected_key = 'D'
keys = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
major_scale = [2, 2, 1, 2, 2, 2, 1]

mark = keys.index(selected_key)
for inc in major_scale:
print((keys + keys)[mark]) # <-- Here is where we double the keys array
mark += inc # to avoid falling off the end.

上述结果将导致:

D
E
F#
G
A
B
C#

关于python - 使用模式迭代列表中的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57600783/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com