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

标签 python python-2.7 nested-lists

目前,下面的代码非常适合获取 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/

相关文章:

Python使用xhtml2pdf将网页打印成PDF

python - 从继承的 QThread 迁移到 Worker 模型

python - for 循环内递增键、值对迭代字典

python - 列表列表更改意外地反射(reflect)在子列表中

python - 如何使用 peewee 创建模型中定义的所有表

python - 将 3D pandas 数据帧转换为 2d

python - 值错误 : invalid literal for long() with base 10: '5B'

css - 如何仅在嵌套列表中的最前面的元素下划线?

javascript - Sencha 触摸2 : Creating a Nested List inside a tab panel

python - 如何执行单个替换,然后使用正则表达式捕获?