如何将元素与列表匹配?

时间:2016-07-01 06:05:52

标签: 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"

4 个答案:

答案 0 :(得分:2)

您不是在相等上匹配,而是在列表中值的子字符串上匹配,假设您只想匹配开头:
注意:假设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"

答案 1 :(得分:0)

首先,修复你的代码:

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

答案 2 :(得分:0)

检查出来:
你要求的单个衬垫和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 - >正确执行!

答案 3 :(得分:0)

一种令人讨厌的,模糊的,较慢的替代方案。 id var似乎是列表项的前缀,但不确定是否需要找到id"某处"在列表元素中。

id  = 77bb1b03
id_list = ['List of devices attached ', '572ea01e\tdevice', '77bb1b03\tdevice', '']
if len(filter(lambda id_list_item: id_list_item.find(id) >=0 , id_list)):
    print "id present"
else:
    print "id not present"