如何使用嵌套列表作为输入?

1 投票
1 回答
604 浏览
提问于 2025-04-18 05:58

目前我有下面的代码,它可以完美地处理两个字符串,并找出它们匹配的部分,结果在输出的第三行中显示。

接下来,我想让代码做的是,从字符串s2中删除从0到第一个匹配字符串结束的位置的部分。举个例子,就是要删除从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)]

1 个回答

1

我不太确定我是否完全明白你的意思,但你可以用下面的内容给我一些提示:

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]

撰写回答