python-3.x - 使用 '<=' 将函数应用于列表
问题描述
我正在尝试将一个函数应用于列表以识别温度低于 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
解决方案
在问这里之前,更广泛地阅读语言的基础知识可能是一个好主意:您可以将任何迭代器转换map
为使用list
. 这解决了您最初的问题。
出现第二个问题是因为您没有考虑范围(另请参阅this)。
如果你想做我理解的事情(即得到一个指示最多 22的bool
数组),那将无济于事:它要么返回,要么返回. 相反,您可能希望使用如下结构:temperature
non_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)))
编辑
如果您愿意,也可以转换bool
为int
使用该int
功能,例如:
print([int(t <= 22) for t in temperature])
推荐阅读
- c - 当我关闭命令提示符时,我在 C 中的基本交易程序不存储任何修改
- java - 一个计时器,多个意图
- reactjs - 如何将图像网格列表添加到类?
- android - 如何确保函数在给定时间运行一次,而不是同时运行?
- asterisk - 如何记录未接电话?Ubuntu 18 + 星号 16 + FreePBX 15
- c# - 如何使用 ImageSharp 添加平铺/重复水印?
- reactjs - 使用流星递归错误过多并做出反应
- javascript - 如何在谷歌图表堆积列中添加链接
- java - log4j 文件在我删除或文件已归档后不会创建
- docker - vagrant up 时出错(docker-compose 插件)