【问题标题】:Using a conditional comprehesion and the re.search function to find all the strings in a list?使用条件理解和 re.search 函数查找列表中的所有字符串?
【发布时间】:2026-01-08 02:35:01
【问题描述】:

我正在尝试使用条件理解和 re.search 函数来查找 DNA_list 中以“ATG”开头并以“TAG”结尾的所有字符串

DNA_list = ['GTCTCTCGA', 'ATGCCTGAAGCATTCTAG', 'GCTGCCCACAAG', 'ATGACTGTAAAACCCTAG']
import re
dna=[print(element)for element in DNA_list if re.search(r'(^ATG)(TAG$)',str(DNA_list))]

但我没有得到输出。我错过了什么?

【问题讨论】:

  • 你想要if re.search(r'(^ATG)(TAG$)', element)。顺便说一句,您应该将列表推导用于副作用,即用于打印。列表推导式用于构建列表。
  • 另外,您需要将您的正则表达式更改为r'(^ATG).*(TAG$)',因为没有.*,它将匹配ATGTAG
  • 另外,构建None 的列表(因为print 返回None)似乎并没有那么高效。
  • 我可能会在这里使用str.startswithstr.endswith[item for item in DNA_list if item.startwith('ATG') and item.endswith('TAG')]
  • 我想要的输出是 '['ATGCCTGAAGCATTCTAG', 'ATGACTGTAAAACCCTAG']'

标签: python list conditional list-comprehension


【解决方案1】:
result = [s for s in DNA_list if re.match(r'^ATG.*TAG$', s)]

【讨论】: