Find an entry in a list based on a partial string

2019-07-28 06:25发布

问题:

I have this list:

item = ['AAA:60', 'BBB:10', 'CCC:65', 'DDD:70', 'EEE:70']

and then I get this string passed to me:

widget = 'BBB'

I'd like to find the entry in item based on widget.

I want to find the entry in the list if widget is contained in any of the list entries. Something where I can use item[i] and preserve the list for the loop it will endure.

Final output would be the list entry itself, BBB:10. (In the example provided.)

回答1:

If you will be doing lots of this searching, please revisit your design. This really should be a dict where the widget name is the key and the 60, 10, 65, etc. values would be the values. You could construct this from your current list using

item_dict = dict((k,int(v)) for k,v in (i.rsplit(':') for i in item))

Then you could easily lookup values using:

item_dict['BBB'] # 10 (already converted to an int)

in operator now does predictable test for existence:

'BBB' in item_dict # True
'BB' in item_dict # False


回答2:

You can try:

>>> item = ['AAA:60', 'BBB:10', 'CCC:65', 'DDD:70', 'EEE:70']
>>> widget = 'BBB'

>>> next(i for i in item if i.startswith(widget))
'BBB:10'

Or if it doesn't necessarily have to begin with "BBB" then you can change the condition to

>>> next(i for i in item if widget in i)
'BBB:10'
>>> next(idx for idx,i in enumerate(item) if widget in i)
1

EDIT: Please also read @PaulMcGuire's answer. In terms of design that is how it should be done.