根据部分字符串在列表中查找条目 [英] Find an entry in a list based on a partial string

查看:72
本文介绍了根据部分字符串在列表中查找条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个列表:

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

然后我将这个字符串传递给我:

and then I get this string passed to me:

widget = 'BBB'

我想根据widgetitem中找到条目.

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

如果任何列表条目中包含widget,我想在列表中找到条目.我可以使用item[i]并保留循环列表的地方.

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.

最终输出将是列表条目本身BBB:10. (在提供的示例中.)

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

推荐答案

如果您将进行很多此类搜索,请重新访问您的设计.这确实应该是一个字典,其中小部件名称是键,而60、10、65等值是值.您可以使用

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运算符现在可以对存在性进行可预测的测试:

in operator now does predictable test for existence:

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

这篇关于根据部分字符串在列表中查找条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆