user5007670
user5007670

Reputation:

how do I match an element with a list?

I am trying to match id with id_list using a one-liner,following doesnt seem to work,how do I fix it?

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"

Upvotes: 1

Views: 246

Answers (4)

terryjbates
terryjbates

Reputation: 312

A nasty, obscure, slower alternative to those that will/are shown. The id var seems to prefix list items, but not sure if you would ever have need to find the id "somewhere" inside a list element.

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"

Upvotes: 0

Devi Prasad Khatua
Devi Prasad Khatua

Reputation: 1235

Check this out:
Single liner as you demanded and id is a string!

>>> 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

Thanks @Achampion for the left -> right execution !

Upvotes: 0

Jan Christoph Terasa
Jan Christoph Terasa

Reputation: 5935

First, fix your code:

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

Then loop over the list and compare each string individually:

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

Upvotes: 0

AChampion
AChampion

Reputation: 30258

You aren't matching on equality but on a substring of the values in the list, assuming you just want to match the start:
Note: assuming id is actually a string because it isn't a valid literal.

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"

Upvotes: 2

Related Questions