1

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

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

what is my index then to item[]? I am trying to wrap this around an IF
@chow - You can simply enumerate the list and fetch your result next(idx for idx,i in enumerate(item) if widget in i).
What if you search for 'BB? You will get a false hit on 'BBB:10' using either startswith or in testing. Safer to test for if i.startswith(widget+':'). This assumes that ':' is not valid as a widget identifier - probably a safe assumption given the ':' delimiter in the item list.
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.