【发布时间】:2018-04-14 15:54:15
【问题描述】:
我有两个小序列,我在“长字符串”中搜索。如果两个序列都找到了,“长字符串”的键被附加到一个列表中(我搜索的字符串是一个字典值)。
现在我正在寻找一种方法来获取/计算两个子字符串之间的距离(如果找到的话)。
所以,例如:
String: ABCDEFGHIJKL
sequence1: ABC
sequence2: JKL
我想得到 DEFGHI 的长度,应该是 6。
这是我查找子字符串的代码,其中包含一些我想要的“伪代码”想法(变量开始和结束)。此代码不起作用(ofc)
def search (myDict, list1, list2):
# initialize empty list to store found keys
a=[]
# iterating through dictionary
for key, value in myDict.items():
# if -35nt motif is found between -40 and -20
for item in thirtyFive:
if item in value[60:80]:
start=myDict[:item]
# it is checked for the -10nt motif from -40 to end
for item in ten:
if item in value[80:]:
end=myDict[:item]
# if both conditions are true, the IDs are
# appended to the list
a.append(key)
distance=start-end
return a, distance
第二个想法: 到目前为止,我发现了一些关于如何在两个子字符串之间获取字符串的内容。所以,我可以想象的下一件事是,获取序列并像 len(sequence) 一样做某事。
所以,我想知道,如果我的第一个想法是在我找到小序列的同时以某种方式做到这一点,是否有可能,并且我的第二个想法是否朝着正确的方向思考。
提前致谢:)
@Carlos 使用 str.find 方法的解决方案
def search (myDict, list1, list2):
# initialize empty list to store found keys
a=[]
# iterating through dictionary
for key, value in myDict.items():
# if -35nt motif is found between -40 and -20
for item in thirtyFive:
if item in value[60:80]:
start=value.find(item)
# it is checked for the -10nt motif from -20 to end
for item in ten:
if item in value[80:]:
end=value.find(item)
# if both conditions are true, the IDs are
# appended to the list
a.append(key)
search.distance=end-start-len(item)
return a
# calling search function
x=search(d,thirtyFive,ten)
#some other things I need to print
y=len(x)
print(str(x))
print(y)
# desired output
print(search.distance)
【问题讨论】:
-
这些开始/停止字符串中的任何一个是否有可能在您的数据中出现不止一次,如果是这样,应该如何处理?
-
因为我限制了可以找到它们的区域,所以它们应该只出现一次。我不是在搜索“任何序列”,它具有生物学背景,因此由于限制,就我而言,序列仅出现一次。如果你的目标是一个通用的解决方案,我认为你是正确的,我不处理这个
标签: python python-3.x substring string-length