If element in list is in in range of another element from another list

╄→гoц情女王★ 提交于 2019-12-13 20:07:29

问题


Below is a question that is an extension of a question I asked a month ago.

Find if item in list a in range of items in sublist of list b

Let's suppose I have two lists:

x = ['2_12_20','2_40_60','4_45_70']
y = ['2_16','2_18','4_60','3_400']

In a biological context, these numbers refer to chromosome positions. For example, in list x, '2_12_20' refers to chromosome 2 between positions 12 and 20.

Similarly, in list y, '2_16' refers to chromosome 2 at position 16.

What I would like to do is determine which chromosome position pairs in y fall within the range in each element in list x.

This is the code I have written so far:

x_new = list(map(lambda z: tuple(map(int,z.split('_'))),x))
y_new = list(map(lambda z: tuple(map(int,z.split('_'))),y))

def check_in_range(number):
    for i in y_new:
        if number[0] == i[0]: #if chromosomes match
             if number[1] <= i[1] and i[1] <= number[2]: #if position falls in range
                 return i
        else:
            continue #if chromosomes do not match, move on to next

answer = dict(zip(x_new, map(check_in_range, x_new)))

I would like my output to return a dictionary, where the elements in x are the keys and the values are any element in y.

My answer should be

{(2, 12, 20): [(2, 16),(2,18)], (2, 40, 60): None, (4, 45, 70): (4, 60)}

But I am getting

{(2, 12, 20): (2, 16), (2, 40, 60): None, (4, 45, 70): (4, 60)}

How do I alter my code so that it updates the dictionary if a key-value pair is already present?


回答1:


I believe I figured it out.

x_new = list(map(lambda z: tuple(map(int,z.split('_'))),x))
y_new = list(map(lambda z: tuple(map(int,z.split('_'))),y))

def check_in_range(number):
    list_a = []
    for i in y_new:
        if number[0] == i[0]: #if chromosomes match
             if number[1] <= i[1] and i[1] <= number[2]: #if position falls in range
             list_a.append(i)
        else:
            continue #if chromosomes do not match, move on to next
   return(list_a)

answer = dict(zip(x_new, map(check_in_range, x_new)))


来源:https://stackoverflow.com/questions/57877954/if-element-in-list-is-in-in-range-of-another-element-from-another-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!