目前,下面的代码非常适合获取 2 个字符串并识别匹配的区域,如输出的第三行所示。
我想说的是,从 0 到第一个匹配字符串结束的代码的下一部分从 s2 中删除此部分,因此对于给定的示例,从 0 到 9 删除。但是,仅当它从 0 开始时才执行此操作。我不确定如何使用嵌套列表,因此解释一下您的代码的作用会很棒。
from collections import defaultdict
from itertools import groupby
def class_chars(chrs):
if 'N' in chrs:
return 'unknown'
elif chrs[0] == chrs[1]:
return 'match'
else:
return 'not_match'
s1 = 'aaaaaaaaaaN123bbbbbbbbbbQccc'
s2 = 'aaaaaaaaaaN456bbbbbbbbbbPccc'
n = 0
consec_matches = []
chars = defaultdict(int)
for k, group in groupby(zip(s1, s2), class_chars):
elems = len(list(group))
chars[k] += elems
if k == 'match':
consec_matches.append((n, n+elems-1))
n += elems
print chars
print consec_matches
print [x for x in consec_matches if x[1]-x[0] >= 9]
输出:
defaultdict(<type 'int'>, {'not_match': 4, 'unknown': 1, 'match': 23})
[(0, 9), (14, 23), (25, 27)]
[(0, 9), (14, 23)]
最佳答案
不确定我完全明白你想要的,但你可以使用以下方式为我指明方向:
In [12]: l=[(0, 9), (14, 23), (25, 27)]
In [13]: flatten_l= [x for y in l for x in y]
In [14]: flatten_l
Out[14]: [0, 9, 14, 23, 25, 27]
# access second tuple arg if first is equal to 0
In [15]: get_num_after=[y[1] for y in l for x in y if x ==0 ]
In [16]: get_num_after
Out[16]: [9]
关于python - 如何使用嵌套列表作为输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23562226/