文字列のリストを のリストに変換してから、dict
次のようなものを使用して検索します。
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
1 行:
>>> 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