You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用<=判断温度列表,map返回对象而非1值列表,需适配SQLite行处理

嘿,我懂你碰到的问题了——Python 3里的map()返回的是一个迭代器对象,不是直接的列表,这就是你看到<map object at 0x100783240>的原因。咱们先解决这个列表生成的问题,再聊聊怎么把这个逻辑用到SQLite数据库里。

解决map返回迭代器的问题

首先,先把你的non_wear_function补全(假设你想给低于22度的温度标记为1,其他为0,你可以根据需求调整返回值):

def non_wear_function(x):
    # 温度低于22度返回1,否则返回0
    return 1 if x < 22 else 0

要得到包含结果的列表,只需要把map对象转换成列表就行——用list()包裹map调用:

temperature = [13, 20, 36, 34, 23, 28, 34, 35, 20]
# 把map迭代器转成列表
non_wear_results = list(map(non_wear_function, temperature))
print(non_wear_results)  # 输出: [1, 1, 0, 0, 0, 0, 0, 0, 1]

如果你觉得map+list的写法不够直观,也可以用列表推导式,效果是一样的:

non_wear_results = [1 if temp < 22 else 0 for temp in temperature]

将逻辑应用到SQLite数据库

接下来把这个温度判断逻辑用到SQLite的温度列上,有几种实用的方式,你可以根据数据量和需求选择:

方式1:先拉取数据到Python再处理

适合数据量不大的情况,先从数据库查询出所有温度值,处理后再写回去:

import sqlite3

# 连接你的SQLite数据库
conn = sqlite3.connect('your_db_name.db')
cursor = conn.cursor()

# 查询所有温度数据
cursor.execute("SELECT temperature FROM your_table_name")
# 把查询结果转成温度列表
db_temperatures = [row[0] for row in cursor.fetchall()]

# 应用函数处理
processed_results = list(map(non_wear_function, db_temperatures))

# 给表新增一列存储结果(如果还没有的话)
cursor.execute("ALTER TABLE your_table_name ADD COLUMN non_wear INTEGER")

# 把处理结果写回数据库(假设表有id列用来定位行,根据你的表结构调整)
for idx, result in enumerate(processed_results):
    cursor.execute("UPDATE your_table_name SET non_wear = ? WHERE id = ?", (result, idx + 1))

# 提交更改并关闭连接
conn.commit()
conn.close()

方式2:在SQLite中注册自定义函数(高效推荐)

如果数据量比较大,没必要把所有数据拉到Python里处理——可以把你的Python函数注册成SQLite能识别的自定义函数,直接在SQL语句中调用:

import sqlite3

def non_wear_function(x):
    return 1 if x < 22 else 0

# 连接数据库
conn = sqlite3.connect('your_db_name.db')
# 注册自定义函数:第一个参数是SQL中要用的函数名,第二个是参数个数,第三个是Python函数
conn.create_function("non_wear", 1, non_wear_function)

cursor = conn.cursor()
# 直接用SQL查询温度和对应的标记
cursor.execute("SELECT temperature, non_wear(temperature) AS non_wear FROM your_table_name")
for temp, flag in cursor.fetchall():
    print(f"温度: {temp}, 非穿戴标记: {flag}")

# 或者直接更新表,把标记写入新列
cursor.execute("ALTER TABLE your_table_name ADD COLUMN non_wear INTEGER")
cursor.execute("UPDATE your_table_name SET non_wear = non_wear(temperature)")

conn.commit()
conn.close()

方式3:直接用SQL条件表达式(最简洁)

如果你的逻辑只是简单的温度判断,甚至不需要写Python函数,直接用SQL的CASE表达式就能搞定,性能最好:

-- 查询时返回标记
SELECT temperature, 
       CASE WHEN temperature < 22 THEN 1 ELSE 0 END AS non_wear 
FROM your_table_name;

-- 新增列并批量更新
ALTER TABLE your_table_name ADD COLUMN non_wear INTEGER;
UPDATE your_table_name SET non_wear = CASE WHEN temperature < 22 THEN 1 ELSE 0 END;

你可以直接在SQLite客户端执行这些语句,或者用Python的cursor.execute()调用。

内容的提问来源于stack exchange,提问作者Romesh Tirimanna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:01:46