【问题标题】:Python - removing everything from a string except certain characters [duplicate]Python - 从字符串中删除除某些字符之外的所有内容[重复]
【发布时间】:2014-03-26 18:34:09
【问题描述】:

不知道之前有没有问过这个问题,但我找不到,所以在这里:

randomList = ["ACGT","A#$..G","..,/\]AGC]]]T"]
randomList2 = []
for i in randomList:
  if i <contains any characters other than "A",C","G", or "T">:
    <add a string without junk to randomList2>

我将如何在 中做所有事情? 谢谢,

【问题讨论】:

标签: python


【解决方案1】:
>>> randomList = ["ACGT","A#$..G","..,/\]AGC]]]T"]
>>> import re
>>> [re.sub("[^ACGT]+", "", s) for s in randomList]
['ACGT', 'AG', 'AGCT']

[^ACGT]+ 匹配除ACGT 之外的一个或多个 (+) 字符。

一些时间安排:

>>> import timeit
>>> setup = '''randomList = ["ACGT","A#$..G","..,/\]AGC]]]T"]
... import re'''
>>> timeit.timeit(setup=setup, stmt='[re.sub("[^ACGT]+", "", s) for s in randomList]')
8.197133132976195
>>> timeit.timeit(setup=setup, stmt='[re.sub("[^ACGT]", "", s) for s in randomList]')
9.395620040786165

没有re,会更快(见@cmd 的回答):

>>> timeit.timeit(setup=setup, stmt="[''.join(c for c in s if c in 'ACGT') for s in randomList]")
6.874829817476666

更快(见@JonClement 的评论):

>>> setup='''randomList = ["ACGT","A#$..G","..,/\]AGC]]]T"]\nascii_exclude = ''.join(set('ACGT').symmetric_difference(map(chr, range(256))))'''
>>> timeit.timeit(setup=setup, stmt="""[item.translate(None, ascii_exclude) for item in randomList]""")
2.814761871275735

也可以:

>>> setup='randomList = ["ACGT","A#$..G","..,/\]AGC]]]T"]'
>>> timeit.timeit(setup=setup, stmt="[filter(set('ACGT').__contains__, item) for item in randomList]")
4.341086316883207

【讨论】:

  • 不要认为+ 需要在那里......
  • @JonClements:它加快了匹配速度,因为不必逐个替换字符。将添加一些时间。
  • 虽然它确实有意义,但对于简单的字符替换,我不会想到会有如此不同。感谢您花时间发布timeits。
  • 我很想知道诸如 ascii_exclude = ''.join(set('ACGT').symmetric_difference(map(chr, range(256)))); for item in randomList: print item.translate(None, ascii_exclude) 之类的东西的表现如何......
  • 可能也是相当讨厌的(但避免加入)...filter(set('ACGT').__contains__, the_string)
【解决方案2】:

re 对此太过分了

randomList2 = [''.join(c for c in s if c in 'ACGT') for s in randomList]

如果你不想要那些最初没有垃圾的东西

valid = set("ACGT")
randomList2 = [''.join(c for c in s if c in valid) for s in randomList if any(c2 not in valid for c2 in s)]

【讨论】:

  • 好点,而且非常优雅。也更快(见我编辑的答案)。
【解决方案3】:

你可以使用正则表达式:

import re
randomList = ["ACGT","A#$..G","..,/\]AGC]]]T"]
nonACGT = re.compile('[^ACGT]')
for i in range(len(randomList)):
    randomList[i] = nonACGT.sub('', randomList[i])
print randomList

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-21
    • 2011-11-08
    • 1970-01-01
    • 2018-03-23
    • 2018-07-15
    • 2018-04-03
    • 2010-10-24
    • 1970-01-01
    相关资源
    最近更新 更多