我对编程很陌生,所以请原谅我的无知。
作为练习,我试着写一个Python程序,它有一个音阶字典和一个和弦字典。这些字典中的键是音阶/和弦的名称,而值是这些音阶/和弦所组成的音符。
我试着寻找这个问题的答案,但到目前为止,我只能找到比较字典值的情况,看看它们是否相等。我想看看一个字典的值是不是另一个字典的值的一部分,如果是,我想让程序显示这些值以及它们所属的键。
scales = {'major': ['1', '2', '3', '4', '5', '6', '7'],
'harmmaj': ['1', '2', '3', '4', '5', 'b6', '7'],
'minor': ['1', '2', 'b3', '4', '5', 'b6', 'b7'],
'harmmin': ['1', '2', 'b3', '4', '5', 'b6', '7'],
'melmin': ['1', '2', 'b3', '4', '5', '6', '7']}
chords = {'minor': ['1', 'b3', '5'],
'm6': ['1', 'b3', '5', '6'],
'm7': ['1', 'b3', '5', 'b7'],
'sus2': ['1', '2', '5'],
'sus4': ['1', '4', '5'],
'maj': ['1', '3', '5'],
'maj6': ['1', '3', '5', '6'],
'maj7': ['1', '3', '5', '7'],
'dom7': ['1', '3', '5', 'b7'],
'dim': ['1', 'b3', 'b5'],
'dim7': ['1', 'b3', 'b5', 'b7'],
'aug': ['1', '3', '#5'],
'aug7': ['1', '3', '#5', 'b7']}
我知道如何用两个字符串做到这一点:
minor = ['1', '2', 'b3', '4', '5', 'b6', 'b7']
m7 = ['1', 'b3', '5', 'b7']
foundmatches = []
for i in range(len(m7)):
if m7[i] in minor:
foundmatches.append(m7[i])
print(foundmatches)
但是我很不知道如何用两个字典来做这个。我尝试遍历两个字典并执行以下操作:
for value in range(len(chords)):
for value in range(len(scales)):
if chords[value] in scales[value]:
print(chords[value])
这会给我一个KeyError,老实说,这可能是一种愚蠢的方法。有人能帮我吗?
如果我理解正确的话,您可能会在这里寻找集合操作,特别是<=
,以查看一个集合是否是另一个集合的子集(和弦是否是音阶的子集):
scales = {
"harmmaj": ["1", "2", "3", "4", "5", "b6", "7"],
"harmmin": ["1", "2", "b3", "4", "5", "b6", "7"],
"major": ["1", "2", "3", "4", "5", "6", "7"],
"melmin": ["1", "2", "b3", "4", "5", "6", "7"],
"minor": ["1", "2", "b3", "4", "5", "b6", "b7"],
}
chords = {
"minor": ["1", "b3", "5"],
"m6": ["1", "b3", "5", "6"],
"m7": ["1", "b3", "5", "b7"],
"sus2": ["1", "2", "5"],
"sus4": ["1", "4", "5"],
"maj": ["1", "3", "5"],
"maj6": ["1", "3", "5", "6"],
"maj7": ["1", "3", "5", "7"],
"dom7": ["1", "3", "5", "b7"],
"dim": ["1", "b3", "b5"],
"dim7": ["1", "b3", "b5", "b7"],
"aug": ["1", "3", "#5"],
"aug7": ["1", "3", "#5", "b7"],
}
for chord_name, chord_spec in chords.items():
chord_spec_set = set(chord_spec)
for scale_name, scale_spec in scales.items():
if chord_spec_set <= set(scale_spec):
print(chord_name, "is in", scale_name)
打印出(按某种顺序)
m6 is in melmin
m7 is in minor
maj is in harmmaj
maj is in major
maj6 is in major
maj7 is in harmmaj
maj7 is in major
minor is in harmmin
minor is in melmin
minor is in minor
sus2 is in harmmaj
sus2 is in harmmin
sus2 is in major
sus2 is in melmin
sus2 is in minor
sus4 is in harmmaj
sus4 is in harmmin
sus4 is in major
sus4 is in melmin
sus4 is in minor