Python&生物学:使用python交叉数据集

时间:2015-01-24 08:04:10

标签: python list

热爱网站。我是一名生物学家,他接受简单的问题并使它们在python中变得复杂,目前仍然存在一个相当简单的问题。我有两个不等的元组列表,其中包含染色体(' chr#')和位置(' start',' end')信息:

list1:length = 1499,tuples =(' chr5',' 12345',' 12678')

list2:length = 75220,tuples =(' chr5',' 44',' 7777777')

如果有人能向我解释为什么这段代码失败了,我可以自己解决这个问题:

list1 = [('chr1', '123', '345'), ('chr1', '567', '678'), ('chr2', '123', 234'),...)

list2 = [('chr1', '123', '567'), ('chr1', '777', '890'), ('chr2', '1', 288'),...)
newlist = []

for j,k,l in list1:
      if j == x for x,y,z in list2:
            if int(k) >= int(y) or int(l) <= int(z):
                 newlist.append(k)
            else:
                 pass
      else:
            pass

推理:我希望比较来自两个字符串的所有元组中的整数,但仅当两个元组的项目[0]匹配时。 我非常感谢任何帮助和提示,谢谢!

3 个答案:

答案 0 :(得分:0)

if list1[0] == list2[0]:
  print 

这是你在找什么? :)

如果您还需要比较数字:

if list1[0] == list2[0]:
    for i in range(1, min([len(list1), len(list2)]):
        if int(list1[i]) < int(list2[i]):
            print('Aha!')

答案 1 :(得分:0)

如果您更改了代码中的第一个if语句,那么它就不会在第二个for循环之前运行代码:

list1 = [('chr1', '123', '345'), ('chr1', '567', '678'), ('chr2', '123', '234')]

list2 = [('chr1', '123', '567'), ('chr1', '777', '890'), ('chr2', '1', '288')]
newlist = []

for j,k,l in list1:
    for x,y,z in list2:
        if j == x:
            if int(k) >= int(y) or int(l) <= int(z):
                newlist.append(k)
            else:
                 pass
        else:
            pass

答案 2 :(得分:0)

我的帖子没有回答你的问题,但我认为你的代码可以通过使用更多的pythonic结构来改进。朝这个方向迈出的第一步是使用命名元组,以便染色体字段可以通过其属性 name start 端:

from collections import namedtuple
Chromosome = namedtuple('Chromosome', ['name', 'start', 'end'])
chromo = Chromosome('chr1', 123, 345)
# You can access the fields as chromo.name, chromo.start and chromo.end

在第二步中,您可以使用列表推导来减少嵌套循环的数量:

from collections import namedtuple

Chromosome = namedtuple('Chromosome', ['name', 'start', 'end'])

list1 = [Chromosome('chr1', 123, 345), Chromosome('chr1', 567, 678), ]
list2 = [Chromosome('chr1', 123, 567), Chromosome('chr2', 1, 288), ]

newlist = []
for chromo1 in list1:
    # Build a list of chromosomes from list2 that
    #  * have the same name as chromo1
    #  * start before chromo1
    #  * end after chromo1
    matches = [chromo2 for chromo2 in list2
               if chromo2.name == chromo1.name and
               (chromo2.start < chromo1.start or chromo2.end > chromo1.end)]
    newlist.extend(matches)