创建包含元素的新列表

2024-04-23 18:28:45 发布

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

所以我想在python程序中实现的是,输入任何碱基与其他无关字符混合的DNA序列,输出一个只有碱基的链,大写。这是我到目前为止一直在写的代码-我是python新手,所以我不知道为什么这个程序不能工作。如果你能给我一些建议,我应该在这里添加什么,使这段代码工作,那将是伟大的。你知道吗

class dnaString (str):
    def __new__(self,s):
        return str.__new__(self,s.upper())
    def bases (list):
        bases = [A,C,T,G]

    def NewStrand (self):
        NewStrand = [self]
        NewStrand = [x for x in NewStrand if x is not A]
        NewStrand = [x for x in NewStrand if x is not C]
        NewStrand = [x for x in NewStrand if x is not T]
        NewStrand = [x for x in NewStrand if x is not G]
        return (NewStrand)

    def printNewStrand (self):
        print ("New DNA strand: {0}".format(self.NewStrand()))

dna = input("Enter a dna sequence: ")
x=dnaString(dna)
x.NewStrand()

Tags: 代码inself程序forifisdef
2条回答

你只需要一个函数。这个函数使用生成器表达式而不是filterlambda,但结果是相同的。你知道吗

>>> def strand(base="ACTG"):
...     """ Return a strand from user input """
...     s = raw_input("Enter a sequence: ")
...     return "".join(x for x in s.lower() if x in base.lower()).upper()
...

>>> strand()
Enter a sequence: asdffeeakttycasdgeadc
'AATTCAGAC'

另一个例子:

>>> strand()
Enter a sequence: asdfsdf29038520395slkdgjw3l4ktjnd,cvmbncv,bhieruoykrjghcxvb
'AGTCCGC

如果您只是想做您正试图做的事情,那么使用类就有点过分了。你知道吗

这就是你所需要的:

bases = 'ATGC'
strand = raw_input("Enter a dna sequence: ")
output = filter(lambda x: x.lower() in bases.lower(), strand)
output = output.upper()
print output

它使用python的^{}函数过滤掉不需要的字符。你知道吗

  • 我们首先在bases中声明允许的字符。你知道吗
  • crap可以是从raw_input()函数接受的任何用户输入。你知道吗
  • output调用函数filter,该函数接受iterable并根据作为第二个参数传递给filter()函数的函数从中筛选出元素。你知道吗
  • ^{}是python中的一个构造,允许您定义小型匿名函数。你知道吗

编辑:

看起来您正在使用Python3。python3中没有定义原始输入,python3中filter返回值的方式也不同。对于Python3,您可以这样做:

bases = 'ATGC'
strand = input("Enter a dna sequence: ")
output = list(filter(lambda x: x.lower() in bases.lower(), strand))
output = ''.join(output)
output = output.upper()
print(output)

相关问题 更多 >