我会将您的字符串列表转换为dict
s 列表,然后使用以下内容进行搜索:
test_pkg_list = [
"""name = git
version = 1.0
description = git package""",
"""name = opengl
version = 1.25
description = graphics"""]
dictlist = []
# Turn into a list of dictionaries
for item in test_pkg_list:
d = {}
for line in item.splitlines():
k, v = line.split('=')
d[k.strip()] = v.strip()
dictlist.append(d)
print dictlist
# [
# {'version': '1.0', 'name': 'git', 'description': 'git package'},
# {'version': '1.25', 'name': 'opengl', 'description': 'graphics'}
# ]
searchname = 'git'
# Now search by name
print any(searchname == x['name'] for x in dictlist)
如果你不想转换成 dict 的麻烦,你可以做一些简单的事情:
>>> searchname = 'git'
>>> print any(searchname in line for line in test_pkg_list)
True
>>> searchname = 'empty'
>>> print any(searchname in line for line in test_pkg_list)
False
>>> searchname = 'version' # This is a problem
>>> print any(searchname in line for line in test_pkg_list)
True
# Or to ensure it only matches the name:
>>> print any('name = ' + searchname in line for line in test_pkg_list)
False
>>> searchname = 'git'
>>> print any('name = ' + searchname in line for line in test_pkg_list)
True
>>> searchname = 'version'
>>> print any('name = ' + searchname in line for line in test_pkg_list)
False
或者您可以只提取名称:
for line in test_pkg_list:
firstline = line.splitlines()[0]
name = firstline.split('=')[1].strip()
print name
一条线:
>>> names = [line.splitlines()[0].split('=')[1].strip() for line in test_pkg_list]
['git', 'opengl']
然后比较:
>>> 'git' in names
True
>>> 'test' in names
False
性能与使用re
: (65% 的速度)相当
>>> timeit.timeit("any(re.search(r'name = ' + 'git', item) for item in p)", "p = ['''name = git\nversion = 1.0\ndescription = git package''', '''name = opengl\nversion = 1.25\ndescription = graphics''']; import re")
2.338025673656987
>>> timeit.timeit("'git' in [line.splitlines()[0].split('=')[1].strip() for line in p]", "p = ['''name = git\nversion = 1.0\ndescription = git package''', '''name = opengl\nversion = 1.25\ndescription = graphics''']")
3.5689878827767245