Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 无法检查值是否在列表中_Python_List - Fatal编程技术网

Python 无法检查值是否在列表中

Python 无法检查值是否在列表中,python,list,Python,List,我有一个返回rs=cur.fetchall的列表,我找不到其中的值“type” rs=[('objectid', 'integer'), ('nameshort', 'character varying'), ('urbanprojectyear', 'character varying'), ('urbanprojectname', 'character varying'), ('notes', 'character varying'), ('scalerank', 'smallint'),

我有一个返回rs=cur.fetchall的列表,我找不到其中的值“type”

rs=[('objectid', 'integer'), ('nameshort', 'character varying'), ('urbanprojectyear', 'character varying'), ('urbanprojectname', 'character varying'), ('notes', 'character varying'), ('scalerank', 'smallint'), ('stylename', 'character varying'), ('firstyear', 'smallint'), ('lastyear', 'smallint'), ('type', 'character varying'), ('name', 'character varying'), ('globalid', 'character varying'), ('created_user', 'character varying'), ('created_date', 'timestamp without time zone'), ('last_edited_user', 'character varying'), ('last_edited_date', 'timestamp without time zone'), ('sde_state_id', 'bigint'), ('shape', 'USER-DEFINED')]
我试过这个和其他几种方法。但它总是转到if语句的else

if 'type' in rs:
    print("True")
else: print("False")

我缺少什么?

rs是元组列表,“type”是字符串。元组永远不等于字符串

# check if 'type' is equal to the first value of any tuple
if 'type' in [t[0] for t in rs]:
    print("True")
else:
    print("False")

rs是元组列表,“type”是字符串。元组永远不等于字符串

# check if 'type' is equal to the first value of any tuple
if 'type' in [t[0] for t in rs]:
    print("True")
else:
    print("False")

这将不起作用,因为rs是嵌套的

一种对初学者友好的方法是使用循环来实现这一点。你也会有创意,一行一行的列表理解,但我会留给你

found = False
for item in rs:
    if 'type' in item:
        found = True

if found:
    print('True')
else:
    print('False')

这将不起作用,因为rs是嵌套的

一种对初学者友好的方法是使用循环来实现这一点。你也会有创意,一行一行的列表理解,但我会留给你

found = False
for item in rs:
    if 'type' in item:
        found = True

if found:
    print('True')
else:
    print('False')

您缺少的是“type”不在rs中,而“type”、“character variabling”在rs中

如果要检查列表中是否有以“type”开头的元组,可以这样做:

print('type' in [x for x, _ in rs])
还有其他更有效但更冗长的方法来解决这个问题,但你明白了

在你的例子中,这个列表似乎是某种更好的表达方式。因此,这可能是最适合你的例子:

dict_rs = dict(rs)
print('type' in dict_rs)

您缺少的是“type”不在rs中,而“type”、“character variabling”在rs中

如果要检查列表中是否有以“type”开头的元组,可以这样做:

print('type' in [x for x, _ in rs])
还有其他更有效但更冗长的方法来解决这个问题,但你明白了

在你的例子中,这个列表似乎是某种更好的表达方式。因此,这可能是最适合你的例子:

dict_rs = dict(rs)
print('type' in dict_rs)

列表中没有“type”,第一个元素是“type”,第二个元素正是我想要的。谢谢你@Grismar!第二个正是我要找的。谢谢你@Grismar!