首页 > 解决方案 > 在另一个元组列表中搜索元组不适用于“in”条件

问题描述

无法弄清楚为什么我的“不在”状态不起作用。我有两个列表(all_cameras 和 some_cameras)。一个包含“Row”类型元素(从数据库中获取:all_cameras = cursor.fetchall()),另一个包含“tuple”类型元素。

目前,列表是相同的,所以第一个项目应该完全匹配;但是,当我进行测试以查看“some_cameras”中的项目是否在“all_cameras”列表中的任何位置时,它总是说找不到。我不能对这种类型的事情使用“in/not in”调节吗?

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

标签: python-3.6

解决方案


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

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

推荐阅读