jul*_*les 5 python dictionary list
我基本上有一个文件夹中所有文件的列表,在简化版本中看起来像:
file_list = [ 'drug.resp1.17A.tag', 'drug.resp1.96A.tag', 'drug.resp1.56B.tag', 'drug.resp2.17A.tag', 'drug.resp2.56B.tag', 'drug.resp2.96A.tag']
Run Code Online (Sandbox Code Playgroud)
另一个清单:
drug_list = [ '17A', '96A', '56B']
Run Code Online (Sandbox Code Playgroud)
我想将这两个列表组合成一个字典,这样:
dictionary = {
'17A' : ['drug.resp1.17A.tag' , 'drug.resp2.17A.tag' ],
'96A' : ['drug.resp1.96A.tag' , 'drug.resp2.96A.tag' ],
'56B' : ['drug.resp1.56B.tag' , 'drug.resp2.56B.tag' ]}
Run Code Online (Sandbox Code Playgroud)
我想这样做却被卡住了!
dict_drugs = {}
for file in file_list:
list_filename = file.split('.')
for elem in drug_list:
if elem in list_filename:
Run Code Online (Sandbox Code Playgroud)
在此之后我可以做什么来将元素加入字典中,或者我完全错误地做了这个?
好吧,你不需要内循环
>>> file_list = [ 'drug.resp1.17A.tag', 'drug.resp1.96A.tag', 'drug.resp1.56B.tag', 'drug.resp2.17A.tag', 'drug.resp2.56B.tag', 'drug.resp2.96A.tag']
>>> dictonary = {}
... for i in file_list:
... k = i.split('.')[-2]
... if k in dictonary:
... dictonary[k].append(i)
... else:
... dictonary[k] = [i]
>>> dictonary
62: {'17A': ['drug.resp1.17A.tag', 'drug.resp2.17A.tag'],
'56B': ['drug.resp1.56B.tag', 'drug.resp2.56B.tag'],
'96A': ['drug.resp1.96A.tag', 'drug.resp2.96A.tag']}
>>>
Run Code Online (Sandbox Code Playgroud)
再检查一下是否只需要drug_list中存在的那些值
表示file_list是否包含:
file_list = [' drug.resp1.18A.tag ','drug.resp1.96A.tag','drug.resp1.56B.tag','drug.resp2.17A.tag','drug.resp2.56B. tag','drug.resp2.96A.tag']
>>> drug_list = [ '17A', '96A', '56B']
... dictonary = {}
... for i in file_list:
... k = i.split('.')[-2]
... if k in drug_list:
... if k in dictonary:
... dictonary[k].append(i)
... else:
... dictonary[k] = [i]
>>>
Run Code Online (Sandbox Code Playgroud)
另一种有效做大写的方法:
dictonary = dict(((i,[]) for i in drug_list))
dictonary = {drug: [] for drug in drug_list} # As @J.F. Sebastian suggested.
for file in file_list:
k = file.split('.')[-2]
if k in dictonary:
dictonary[k].append(file)
Run Code Online (Sandbox Code Playgroud)