如何将元素与列表匹配?

2024-04-25 21:58:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用一行代码将idid_list匹配,下面的代码似乎不起作用,如何修复它?你知道吗

id  = 77bb1b03
id_list = ['List of devices attached ', '572ea01e\tdevice', '77bb1b03\tdevice', '']
if id in id_list:
     print "id present"
else:
     print "id not present"

Tags: of代码inidifnotelselist
2条回答

看看这个:
你需要的是一行代码,id是一个字符串!你知道吗

>>> from __future__ import print_function
... id  = '77bb1b03'
... id_list = ['List of devices attached ', '572ea01e\tdevice', '77bb1b03\tdevice', '']
... [print(item, 'ID present') for item in id_list if item and item.find(id)!=-1]
77bb1b03    device ID present

感谢@Achampion的左-右执行!你知道吗

首先,修复代码:

id  = "77bb1b03" # needs to be a string
id_list = ['List of devices attached ', '572ea01e\tdevice', '77bb1b03\tdevice', '']

然后在列表上循环并分别比较每个字符串:

for s in id_list:
    if id in s:
        print "id %s present"%id
        break
else:
    print "id %s not present"%id

假设您只想匹配起始值:
注意:假设id实际上是一个字符串,因为它不是有效的文本。你知道吗

id  = '77bb1b03'
id_list = ['List of devices attached ', '572ea01e\tdevice', '77bb1b03\tdevice', '']
if any(i.startswith(id) for i in id_list):
    print "id present"
else:
    print "id not present"

相关问题 更多 >