首页 > 解决方案 > 使用 '<=' 将函数应用于列表

问题描述

我正在尝试将一个函数应用于列表以识别温度低于 22 度的所有实例。我想将此函数应用于 SQLite 数据库的一行。我曾尝试使用 map 函数,但这会返回结果<map object at 0x100783240>而不是带 1 的列表。

这是我在连接到 SQLite 数据库之前练习的输入:

temperature = [13, 20, 36, 34, 23, 28, 34, 35, 20]

这是其余的代码:

def non_wear_function(x):
    nonwear = []
    if temperature <= 22:
        nonwear.append(1)
        return nonwear

print(map(non_wear_function, temperature))

当我尝试像这样打印非磨损列表时:

Print(nonwear) 

它给出了错误

Name error: non wear function not defined

标签: python-3.xlistfunctiondictionary

解决方案


在问这里之前,更广泛地阅读语言的基础知识可能是一个好主意:您可以将任何迭代器转换map为使用list. 这解决了您最初的问题。

出现第二个问题是因为您没有考虑范围(另请参阅this)。

如果你想做我理解的事情(即得到一个指示最多 22的bool数组),那将无济于事:它要么返回,要么返回. 相反,您可能希望使用如下结构:temperaturenon_wear_function[1]None

def non_wear_function(t):
    return (t <= 22)

print(list(map(non_wear_function, temperature)))

尽管在这种情况下,使用 lambda 函数或推导式可能更适合:

print([(t <= 22) for t in temperature])
print(list(map(lambda t: (t <= 22), temperature)))

编辑

如果您愿意,也可以转换boolint使用该int功能,例如:

print([int(t <= 22) for t in temperature])

推荐阅读