根据字典检查变量,并打印剩余的字典内容

Check variables against a dictionary, and print the dictionary contents remaining

我想根据字典检查用户输入,然后打印字典中仍然存在但用户未输入的值。

这是我的代码,它接受用户输入,根据字典检查它并将它发送到下面的打印功能。

    elif choice == '7':
    print("Enter at least 4 pitches")
    set1 = str(input("Enter first pitch: "))
    set2 = str(input("Enter second pitch: "))
    set3 = str(input("Enter third pitch: "))
    set4 = str(input("Enter fourth pitch: "))
    set5 = str(input("Enter fifth pitch or type 'Done': "))
    if set5 == 'Done':
        setset1 = f(set1)
        setset2 = f(set2)
        setset3 = f(set3)
        setset4 = f(set4)

        setc4(setset1, setset2, setset3, setset4)

这是我的函数,打印在字典中找到的内容,然后打印剩下的内容。

def setc4(vset1, vset2, vset3, vset4):
print(" ")
print("The complement of the four note set")
print(vset1, vset2, vset3, vset4)
print("is")

基本上我需要检查用户输入(即 A 和 B)然后打印字典中除 A 和 B 之外的所有其他内容(即 C、D 和 E)的功能。本质上,我是 运行 'set' 和 'complement' 分析,用户输入集合,然后打印该集合的补集。

解决此问题的最佳方法是什么?谢谢!

这是我的 'notes' 词典。

notes = {
'Bs': 0,
'C': 0,
'Cs': 1,
'Db': 1,
'D': 2,
'Ds': 3,
'Eb': 3,
'E': 4,
'Fb': 4,
'Es': 5,
'F': 5,
'Fs': 6,
'Gb': 6,
'G': 7,
'Gs': 8,
'Ab': 8,
'A': 9,
'As': 10,
'Bb': 11,
'B': 11,
}

如果我没理解错的话,你可以直接使用dict.pop()pop returns 指定键的值,然后将其从字典中删除。如果字典中不存在指定的键,则默认为 return None。

a_dict = {'a': 1, 'b': 2, 'c': 3}

print(a_dict.pop('a'))
>> 1
print(a_dict)
>> {'c': 3, 'b': 2}

使用 difference 函数计算集合差异。

number_of_inputs = ...
inputs = []
dictionary = {...}

def print_diff():
    for i in range(number_of_inputs + 1):
        inputs.append(str(input("enter pitch {}".format(i + 1))))
    if inputs[-1] == 'Done':
        del inputs[-1]
        diff = dictionary.difference(set(inputs))
        print('The complement is ')
        for element in diff:
            print(element)

例如:

>>> number_of_inputs = 4
>>> dictionary = {'one', 'two', 'three', 'four', 'five', 'six', 'seven'}
>>> print_diff()

enter pitch 1
three
enter pitch 2
five
enter pitch 3
one
enter pitch 4
five
enter pitch 5
Done
The complement is
two
four
six
seven

请注意,底层字典数据结构不是 dict,而是 set。这是因为您并不真正需要键值对中的键。由于您实际拥有的字典是 dict 您可以删除键并将其转换为一个集合,如下所示:

dictionary = set(dictionary.values())

根据您对问题所做的编辑,字典中的值类型与您从用户输入的值类型不匹配。具体来说,你得到 strs,但你有一个 ints 的字典。您可以将字典转换为一组 str 或从用户那里检索 int

将字典从一组 int 转换为一组 str 可以按如下方式完成:

dictionary = {str(i) for i in dictionary}

(你应该在dictionary = set(dictionary.values())之后执行上面的行)

从用户那里检索 ints 而不是 strs 可以按如下方式完成:

int(input("enter pitch {}".format(i + 1)))

而不是

str(input("enter pitch {}".format(i + 1)))