简体   繁体   English

为什么在尝试与字典值进行比较时出现错误?

[英]Why am I getting an error when trying to compare to dictionary values?

I'm supposed to:我应该:

Write a function, precipiation(d, a, b) that takes parameters:写一个带参数的 function, precipiation(d, a, b):

d: Dictionary mapping a season to an amount of precipitation for that season. d:字典将季节映射到该季节的降水量。 a: One season b: Another season a: 一个季节 b: 另一个季节

Your function should return True if the rainfall in season a was greater than it was in season b, and False otherwise.如果 a 季节的降雨量大于 b 季节的降雨量,您的 function 应该返回 True,否则返回 False。 If the rainfall was equal, return False.如果降雨量相等,则返回 False。

Your function should handle the following errors the following ways:您的 function 应通过以下方式处理以下错误:

If either a or b is not a valid season in the dictionary, you should return an error message (as a string) formatted exactly as: "Error: Key is not in Dictionary."如果 a 或 b 不是字典中的有效季节,则应返回错误消息(作为字符串),格式完全为:“错误:键不在字典中”。

If the values for the rainfall in each season are not valid for comparison, that is, one of them is not a number, return an error message (as a string) formatted exactly as: "Error: Invalid data types in Dictionary?"如果每个季节的降雨量值对比较无效,即其中一个不是数字,则返回错误消息(作为字符串),格式完全为:“错误:字典中的数据类型无效?”

You may assume that no test case will produce both types of errors (so you do not need to decide whether or not to return a Key Error or Invalid Type error when you encounter both).您可以假设没有测试用例会同时产生这两种类型的错误(因此当您遇到两种错误时,您无需决定是否返回 Key Error 或 Invalid Type 错误)。 However, you should not make any assumptions about the seasons that exist--sometimes there may be a 'potato' season.但是,您不应该对存在的季节做出任何假设——有时可能会有一个“马铃薯”季节。

I wrote a function that is mostly correct我写了一个 function 大部分是正确的

def precipitation(d, a, b):

    try:
        if d[a] > d[b]:
            return True
        else:
            return False

    except:
        if a not in d or b not in d:
            return ("Error: Key is not in Dictionary.")

        if d[a] not in (int) or d[b] not in (int):
            return ("Error: Invalid data types in Dictionary?")

When I run this function with test case当我用测试用例运行这个 function

precipitation({"Spring": 'cats', "Summer": 313, "Fall": 1457, "Winter": 354}, "Summer", "Spring") == 'Error: Invalid data types in Dictionary?'

I get an error argument of type 'type' is not iterable How can I fix this and what is causing the problem我得到一个argument of type 'type' is not iterable我该如何解决这个问题以及导致问题的原因

This is your problem:这是你的问题:

if d[a] not in (int) 

int is not a container, it's a type, so d[a] can't be in it.* int不是容器,它是一种类型,所以d[a]不能在其中。*

Are you trying to make sure it's an integer?您是否要确保它是 integer? Then try isinstance() :然后尝试isinstance()

if not isinstance(d[a], int) ...

* You could write a metaclass that had a __contains__() method that let you treat types as containers and check for instance types in this way, which is actually a kind of interesting idea, but int does not do that. * 您可以编写一个具有__contains__()方法的元类,让您将类型视为容器并以这种方式检查实例类型,这实际上是一种有趣的想法,但int不会这样做。

In addition to the correct answers already provided,除了已经提供的正确答案,
since you are using try and except , you can also specify the type of exception for each block as well:由于您使用的是tryexcept ,您还可以为每个块指定异常类型:

def precipitation(d, a, b):
    try:
        return d[a] > d[b]
    except KeyError:
        return "Error: Key is not in Dictionary."
    except TypeError:
        return "Error: Invalid data types in Dictionary?"

To check if a parameter is a specific type, use isinstance - in checks if a specific value is present in an iterable.要检查参数是否为特定类型,请使用isinstance - in检查可迭代对象中是否存在特定值。

if not isinstance(d[a], int) or not isinstance(d[b], int):
    return ("Error: Invalid data types in Dictionary?")

use this as this is exact way of error handling使用它,因为这是错误处理的确切方式

if ValueError:
    return ("Error: Invalid data types in Dictionary?")

instead of代替

if if d[a] not in (int) or d[b] not in (int):
    return ("Error: Invalid data types in Dictionary?")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么在尝试比较两个列表时出现错误? - Why am I receiving an error when trying to compare two lists? 为什么我在索引字典时会收到“字符串索引必须是整数”错误? - Why am I getting a “String indices must be integers” error when I am indicing a dictionary? 尝试将字典中的 output 值与数字进行比较时出现错误 - TypeError: '>' not supported between 'tuple' 和 'int' 实例 - Trying to compare output value from a dictionary to a number I am getting error- TypeError: '>' not supported between instances of 'tuple' and 'int' 为什么我在尝试运行我的 Discord 机器人时会收到此错误 - Why am I getting this error when I am trying to run my Discord bot 尝试插入while循环时为什么会出现错误? - Why am I getting an error when I am trying to insert a while loop? 当我尝试将字符串插入列表时,为什么会出现此错误? - Why am i getting this error when i am trying to insert a string into a list? 我正在尝试制作基于 GUI 的字典,但出现以下错误 - I am trying making GUI based dictionary,but getting following error 有谁知道为什么我在尝试将列表转换为字典时会收到此错误? - Does anyone know why I am receiving this error when trying to convert a list to a dictionary? 为什么我仅在字典的第一个键中获取值? - Why am i getting values in my first key of the dictionary only? 尝试替换时出现类型错误 - I am getting a type error when I am trying to replace
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM