【问题标题】:If Statement - Is this a string?If 语句 - 这是一个字符串吗?
【发布时间】:2013-09-11 06:06:17
【问题描述】:

我有几个字典集,每个都有相同的键和不同的定义。

尝试编写一个函数来确定键的定义是字符串还是列表。

什么都不打印...

lloyd = {
    "name": "Lloyd",
    "homework": [90.0, 97.0, 75.0, 92.0],
    "quizzes": [88.0, 40.0, 94.0],
    "tests": [75.0, 90.0]
}
alice = {
    "name": "Alice",
    "homework": [100.0, 92.0, 98.0, 100.0],
    "quizzes": [82.0, 83.0, 91.0],
    "tests": [89.0, 97.0]
}
tyler = {
    "name": "Tyler",
    "homework": [0.0, 87.0, 75.0, 22.0],
    "quizzes": [0.0, 75.0, 78.0],
    "tests": [100.0, 100.0]
}

students = [lloyd,alice,tyler]

def compute_grades(ourstudents):
    for item in ourstudents:
        if item["name"] == type(str):
            print "YES"

compute_grades(students)

在这种情况下如何使用 if 语句来确定是字符串还是列表?

【问题讨论】:

    标签: python string list function types


    【解决方案1】:

    使用isinstance:

    >>> isinstance("foo", str) #Use basestring in py2.x
    True
    >>> isinstance([1, 2, 3], list)
    True
    

    【讨论】:

    • 让我们试一试
    • 我想知道……当各种事情发生变化时,isinstance是未来的最终开发吗?
    • 如果 isinstance(item, str) == True:
    • @NicholasHazel 仅使用 str 将无法处理 py2.x 中的 unicode 字符串
    • @NicholasHazel item 在你的情况下是 dict,所以,isinstance(item, str) 将是 False
    【解决方案2】:
    if item["name"] == type(str):
    

    这有两个问题:

    • 您正在比较“名称”字段的,而不是类型
    • 您将它与str 的类型进行比较; str 本身就是字符串类型,所以type(str)是类型类型,你可以在这里看到:

      >>> type("Alice")
      <type 'str'>
      >>> str
      <type 'str'>
      >>> type(str)
      <type 'type'>
      

    由此可以看出"Alice" == type(str)一定是假的。

    如果需要,在 python 中检查类型的首选方法是使用isinstance(&lt;value&gt;, &lt;type&gt;);例如:

    >>> isinstance("Alice", str)
    True
    

    【讨论】:

    • 如果 isinstance(item, str) == True:
    • A == True 如果 A 为真,则为真,如果 A 为假,则为假,表达式 A == True 与布尔 A 的 A 相同。
    【解决方案3】:

    type 应用于比较的另一个参数。

    if type(item["name"]) == str:
    

    【讨论】:

    • GJ。那么,isinstance 和 type 有区别吗?
    • @NicholasHazel:是的。 isinstance 还检查对象是否属于派生类。与type 比较,检查它是否是完全相同的类的实例。
    • .. 说得很好,先生。谢谢
    猜你喜欢
    • 2017-06-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-09
    • 2016-07-17
    • 1970-01-01
    • 1970-01-01
    • 2019-04-25
    • 2012-09-05
    相关资源
    最近更新 更多