小编jul*_*les的帖子

如果模式匹配,则将两个列表组合到字典中

我基本上有一个文件夹中所有文件的列表,在简化版本中看起来像:

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)

在此之后我可以做什么来将元素加入字典中,或者我完全错误地做了这个?

python dictionary list

5
推荐指数
1
解决办法
493
查看次数

附加多个文件并使用词典删除重复项

所以我有一些文件看起来像:

snpID  Gene
rs1  ABC1
rs2  ABC1
rs3  ABC25
rs4  PT4
rs5  MTND24
Run Code Online (Sandbox Code Playgroud)

在不同的文件中,将存在其他snpID和基因对,但是对于给定的snpID可能存在重复,但相关联的"基因"可能不同.例如:

snpID  Gene
rs100  URX1
rs95  KL4
rs1  ABC1
rs2  ABC1-MHT5
rs3  ABC25
rs4  PT4-FIL42
Run Code Online (Sandbox Code Playgroud)

我想要做的是附加文件的所有内容,如果它们具有相同的snpID和Gene对,则删除重复项.然而,如果snpID的相应基因不同,则它必须进入同一行.对于上面的示例,它应该如下所示:

snpID  Gene
rs1  ABC1
rs2  ABC1, ABC1-MHT5
rs3  ABC25
rs4  PT4, PT4-FIL42
rs5  MTND2
rs100  URX1
rs95  KL4
Run Code Online (Sandbox Code Playgroud)

我以为我可以通过创建词典来实现这一目标.

import glob
file_list = glob.glob('annotations.*')
dict_snps_genes = {}
for filename in file_list:
    with open(filename) as fileA:
        for line in fileA:
            col0 = line.split()[0]
            col1 = line.split()[1]
            dict_snps_genes[col0] = col1 

unique_dict_snps = {} …
Run Code Online (Sandbox Code Playgroud)

python merge dictionary duplicate-removal

2
推荐指数
1
解决办法
1123
查看次数

计算多个文件中的行并输出文件名

我想获取文件夹中每个文件中的行数,然后相邻地打印出行数和文件名.刚刚进入编程世界,我设法编写了这个简短的代码,从这里和那里借用它们.

#count the number of lines in all files and output both count number and file name
import glob
list_of_files = glob.glob('./*.linear')
for file_name in list_of_files:
    with open (file_name) as f, open ('countfile' , 'w') as out :
        count = sum (1 for line in f)
        print >> out, count, f.name
Run Code Online (Sandbox Code Playgroud)

但是这只给出了一个文件的输出.

这可以很容易地wc -l *在shell中使用.linear,但我想知道如何在python中执行此操作.

PS:我真诚地希望我不是重复的问题!

python count

1
推荐指数
1
解决办法
1669
查看次数

标签 统计

python ×3

dictionary ×2

count ×1

duplicate-removal ×1

list ×1

merge ×1