1

给定一个数字和一个字典,“remove_numbers_larger_than”会删除其值为大于给定数字的数字的任何键。返回修改后的字典。

inp = {'a': 8, 'b': 2, 'c': 'montana'}

remove_numbers_larger_than(5, inp)

print(inp) # --> {'b': 2, 'c': 'montana'}

我的问题是我不知道如何使用 inp 字典中的字符串来执行此操作。

def remove_numbers_larger_than(number, dictionary):
    for k, v in dictionary.items():
        if type(v) == str:
            continue 
        if type(v) == int and v > number:
            del[k]
        
    return dictionary 

这是我到目前为止所拥有的,我不确定我是否朝着正确的方向前进。感谢您在我的学习过程中提供的任何帮助。

4

2 回答 2

1

您可以isinstance根据dtype. 这是一种使用字典理解的方法:

{k:v for k,v in inp.items() if not (isinstance(v, int) and (v>5))}
# {'b': 2, 'c': 'montana'}

这相当于以下for循环:

d = dict()
for k,v in inp.items():
    if not (isinstance(v, int) and (v>5)):
        d[k] = v
于 2020-07-06T12:53:13.773 回答
1

这应该做你需要的:

dic = {'a': 8, 'b': 2, 'c': 'montana'}
def remove_numbers_larger_than(number, dictionary):
    return {key: value for key, value in dictionary.items() if not (isinstance(value, int) and value > number)}
print(remove_numbers_larger_than(2, dic))
# output: {'b': 2, 'c': 'montana'}

以下是相同的,但写得更容易理解:

def remove_numbers_larger_than(number, dictionary):
    newDict = {}

    # looping over the keys and values of the dictionary
    for key, value in dictionary.items():

        # checking if 1st the value is an integer and if so we secondly check if it is higher than 'number'
        # note that we put both checks into braces, because of the "not" statement.
        # if we wouln't put it into braces the "not" would only get applied to the first statemtent,
        # but we want it to apply to the result of both checks together
        if not (isinstance(value, int) and value > number):
            newDict[key] = value

    return newDict
print(remove_numbers_larger_than(2, dic))
# output: {'b': 2, 'c': 'montana'}

祝你好运!

于 2020-07-06T13:00:04.770 回答