对多个列表的列表进行列表推导
我遇到了一个很棘手的列表推导问题,怎么也解决不了。现在我有两个列表,长得像这样:
a=[[....],[....],[....]]
b=[[....],[....],[....]]
len(a)==len(b) including sublists i.e sublists also have the same dimension.
现在我想做一个正则表达式的编译,像这样:
[re.compile(_subelement_in_a).search(_subelement_in_b).group(1)]
我在想怎么能用列表推导来实现上面的功能,像这样:
[[re.compile(str(x)).search(str(y)).group(1) for x in a] for y in b]
..但显然上面的方式不行,我在想有没有人能给我指条明路。
编辑
我刚意识到,列表b中的子列表比列表a中的子列表多了元素。所以,比如说:
a=[[1 items],[1 items],[1 items]]
b=[[10 item], [10 item], [10 item]]
我还是想做和我之前问题一样的事情:
[[re.compile(str(x)).search(str(y)).group(1) for x in b] for y in a]
而输出应该是这样的:
c = [[b[0] in a[0] items],[b[1] in a[1] items],[b[2] in a[2] items]]
举个例子:
a=[["hgjkhukhkh"],["78hkugkgkug"],["ukkhukhylh"]]
b=[[r"""a(.*?)b""",r"""c(.*?)d""",r"""e(.*?)f""",r"""g(.*?)h""",r"""i(.*?)j"""],[r"""k(.*?)l""",r"""m(.*?)n""",r"""o(.*?)p""",r"""q(.*?)r"""],[r"""s(.*?)t""",r"""u(.*?)v""",r"""x(.*?)y""",r"""z(.*?)>"""]]
使用一对一的映射。也就是说检查是否:
elements of sublists of b[0] are present in sublist element of a[0]
elements of sublists of b[1] are present in sublist element of a[1]
elements of sublists of b[2] are presnet in sublist element of a[2]
2 个回答
2
多多使用 zip
函数:
[[re.search(x, y).group(1) for x,y in zip(s,t)] for s,t in zip(a,b)]
第一次使用 zip(a,b)
会生成一对对的小列表。第二次使用 zip
则是把这些小列表中的元素一一对应地配对在一起。
3
听起来你是在找 zip
呢?它的作用是把两个列表配对,变成一个包含配对的列表。
[
[my_operation(x,y) for x,y in zip(xs, ys)]
for xs, ys in zip(a, b)
]
-- 编辑:需求变了:
[
[[regex(p, s) for p in patterns] for s in strings]
for strings, patterns in zip(a, b)
]