问题描述
下面是一个问题,是我一个月前提出的问题的延伸.
Below is a question that is an extension of a question I asked a month ago.
假设我有两个列表:
x = ['2_12_20','2_40_60','4_45_70']
y = ['2_16','2_18','4_60','3_400']
在生物学上,这些数字是指染色体位置.例如,在列表x
中,'2_12_20'
指位置12和20之间的2号染色体.
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.
类似地,在列表y
中,'2_16'
指第16位的2号染色体.
Similarly, in list y
, '2_16'
refers to chromosome 2 at position 16.
我想做的是确定y
中的哪些染色体位置对在列表x
中每个元素的范围内.
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)))
我希望输出返回一个字典,其中x
中的元素是键,而值是y
中的任何元素.
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
.
我的答案应该是
{(2, 12, 20): [(2, 16),(2,18)], (2, 40, 60): None, (4, 45, 70): (4, 60)}
但是我得到了
{(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?
推荐答案
我相信我已经解决了.
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)))
这篇关于如果列表中的元素在另一个列表中的另一个元素的范围内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!