python - If 语句 - 这是一个字符串吗?

标签 python string list function types

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

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

什么都不打印...

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 语句来确定它是字符串还是列表?

最佳答案

使用isinstance:

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

关于python - If 语句 - 这是一个字符串吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18669641/

相关文章:

python - 为什么 int 转换比 pandas 中的 float 慢得多?

python - 如何使用 tf.data 创建多元时间序列数据集?

java - 为什么我不能将 String 转换为 int?

java - 验证用户的字符串类型 'menu choice'

python - 将不同的列表数据类型连接成字符串

python - 在列表中查找行 - python

python - scikit-learn GridSearchCV best_score_ 是如何计算的?

c - 如何按字典顺序对结构中的字符串进行排序?

r - 如何在 R 中将字符串转换为列表

c# - 如何从列表中查找倒数第二个元素?