在另一个元组列表中搜索元组不适用于"in"条件



无法弄清楚为什么我的"不在"条件不起作用。我有两个列表(all_cameras和some_cameras(。一个包含"行"类型元素(从数据库中获取:all_cameras = cursor.fetchall(((,另一个包含"元组"类型元素。

目前,列表是相同的,因此第一个项目应该彼此完全匹配;但是,当我进行测试以查看"some_cameras"中的项目是否在"all_cameras"列表中的任何地方时,它总是说它没有找到。我不能对这类事情使用"在/不在"条件反射吗?

for v_c in some_cameras:
logging.info("Checking if this item is in the all_cameras tuple:")
logging.info(v_c)
logging.info("{} is the first element in the all_cameras list".format(all_cameras[0]))
if v_c not in all_cameras:
logging.info("{} was not found in the all_cameras tuple".format(v_c))

日志输出:

[2020-01-16 12:40:53,588] INFO - MainThread - root - Checking if this item is in the all_cameras tuple:
[2020-01-16 12:40:53,591] INFO - MainThread - root - ('computer', 'cam', '192.168.0.1', 1, '00000000-0000-0000-0000-accc8e741751')
[2020-01-16 12:40:53,603] INFO - MainThread - root - ('computer', 'cam', '192.168.0.1', 1, '00000000-0000-0000-0000-accc8e741751') is the first element in the all_cameras list
[2020-01-16 12:40:53,605] INFO - MainThread - root - ('computer', 'cam', '192.168.0.1', 1, '00000000-0000-0000-0000-accc8e741751') was not found in the all_cameras tuple

看来你不能做我想做的事情,因为它是一个"行"和一个"元组"正在比较。我更新了我的代码,使每个列表都成为列表列表,现在它按预期工作。我用来转换 SQL 输出的代码是:

all_cameras = cursor.fetchall()  # list of Rows
all_cameras = [list(item) for item in all_cameras]  # list of Lists

最新更新