使用enumerate迭代列表字典以提取信息

时间:2015-06-19 18:01:03

标签: python dictionary enumerate

我今天早些时候得到了一些关于如何使用enumerate()从字典中获取位置信息的帮助。我将很快提供代码。但是,既然我已经找到了这个很酷的工具,我想以不同的方式实现它,以便从我的字典中获取更多信息。

我有一本字典:

length = {'A': [(0,21), (30,41), (70,80), (95,200)] 'B': [(0,42), (70,80)]..etc}

和文件:

A    73
B    15
etc

我现在想要做的是找到我的列表中第一个元素的最大值与第二个元素的最小值的差值。例如,差异为21和30.然后我想添加所有这些差异,直到我达到我的文件中的数字匹配的数字对(范围)(如果这是有意义的)。

以下是我一直致力于的代码:

import csv
with open('Exome_agg_cons_snps_pct_RefSeq_HGMD_reinitialized.txt') as f:
    reader = csv.DictReader(f,delimiter="\t")
    for row in reader:
        snppos = row['snp_rein']
        name = row['isoform']
        snpos = int(snppos)
        if name in exons:
            y = exons[name]
            for sd, i  in enumerate(exons[name]):
                while not snpos<=max(i):
                    intron = min(i+1) - max(i) #this doesn't work unfortunately. It says I can't add 1 to i
                    totalintron = 0 + intron
                if snpos<=max(i):
                    exonmin = min(i)
                    exonnumber = sd+1
                    print exonnumber,name,totalintron
                    break

我认为这是让我感到困惑的sd(索引器)。我不知道如何在这种情况下使用它。注释掉的部分是我尝试但未能成功的其他途径。有帮助吗?我知道这是一个令人困惑的问题,我的代码可能有些混乱,但那是因为我甚至无法得到输出来纠正我的其他错误。

我希望我的输出基于提供的文件看起来像这样:

exon   name    introntotal    
3    A    38
1    B    0

2 个答案:

答案 0 :(得分:1)

试图为这个问题提供一些帮助:问题的一个关键部分是我不认为枚举符合你的想法。枚举您正在迭代的事物的数字。所以当你经历你的for循环时,sd将首先为0,然后它将为1 ......而这就是全部。在你的情况下,你想看看相邻的列表条目(似乎?),所以在python中循环的更惯用的方式几乎不是那么干净。所以你可以这样做:

...
y = exons[name]

for index in range(len(y) - 1): # the - 1 is to prevent going out of bounds
    first_max = max(y[index])
    second_min = min(y[index+1])
    ... # do more stuff, I didn't completely follow what you're trying to do

我会为硬核pythonistas添加,你当然可以做一些聪明的东西来写这个更惯用并避免我写的C风格循环,但我认为进入zip等等可能会有点混乱有人刚接触python。

答案 1 :(得分:0)

问题在于您错误地使用enumerate()的输出。

enumerate()首先返回索引(位置),然后返回项目

例如:

x = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
for i, item in enumerate(x):
    print(i, item)

# prints
#(0, 10)
#(1, 11)
#(2, 12)
#(3, 13)
#(4, 14)
#(5, 15)
#(6, 16)
#(7, 17)
#(8, 18)
#(9, 19)

因此,在您的情况下,您应该切换isd

for i, sd in enumerate(exons[name]):
    # do something

与其他评论者建议的一样,阅读python文档通常是开始解决问题的好地方,特别是如果您不确定某个函数是如何完成它的作用的那样:)