正则表达式与列表中的元素进行迭代匹配

2024-05-19 18:49:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列表如下:

mylist = [
    'Th2 2w, total RNA (linc-sh36)',
    'SP CD8, total RNA (replicate 1)',
    'DN 2, total RNA (replicate 2)']

我要做的是在该列表中保留与另一个列表匹配的条目:

ctlist = ['DN 1', 'DN 2', 'DN 3', 'DN 4', \
          'DP 1', 'DP 2', 'tTreg', 'CD8', 'CD4', 'iTreg']

最终的结果是:

 SP CD8, total RNA (replicate 1)
 DN 2, total RNA (replicate 2)

我试过了,但没有结果:

import re
for mem in mylist:
    for ct in ctlist:
      regex = re.compile(ct)
      match = regex.match(mem)
      if match:
         print mem

正确的方法是什么?你知道吗


Tags: inre列表formatchmemsprna
3条回答

这里不需要正则表达式:

>>> mylist
['Th2 2w, total RNA (linc-sh36)', 'SP CD8, total RNA (replicate 1)', 'DN 2, total RNA (replicate 2)']
>>> ctlist
['DN 1', 'DN 2', 'DN 3', 'DN 4', 'DP 1', 'DP 2', 'tTreg', 'CD8', 'CD4', 'iTreg']
>>> [ x for x in mylist for y in ctlist if y in x]
['SP CD8, total RNA (replicate 1)', 'DN 2, total RNA (replicate 2)']

主要的问题是您忘记了mylist中的逗号。所以你的数据不是你想的那样。尝试添加一些print语句,您可以很容易地在循环中发现这样的问题。你知道吗

第二个问题是需要regex.search而不是regex.match,因为您试图匹配整个字符串,而不仅仅是mem的开头。但是,您所做的事情根本不需要正则表达式:

for mem in mylist:
    for ct in ctlist:
        if ct in mem:
            print mem
            break
mylist = ['Th2 2w, total RNA (linc-sh36)','SP CD8, total RNA (replicate 1)','DN 2, total RNA (replicate 2)']
ctlist = ['DN 1', 'DN 2', 'DN 3', 'DN 4','DP 1', 'DP 2', 'tTreg', 'CD8', 'CD4', 'iTreg']
print [ x for x in mylist if [y for y in ctlist if y in x ]]

相关问题 更多 >