简体   繁体   English

一次打印输出后如何脱离python综合列表

[英]How to break out of python comprehensive list after printing the output once

Here is my code to print the reverse of DNA sequence, only if the string 这是我的代码,用于打印DNA序列的反向字符,仅当字符串为

contain character ["A","T","G","C"]

dna=input("Enter DNA sequnce")
[print(dna[::-1]) for x in dna if x in["A","T","G","C"]]

input: ATGC

the output:
CGTA
CGTA
CGTA
CGTA

How do I prevent the code from looping the number of characters present in the string. 如何防止代码循环出现在字符串中的字符数。 Can I get the output once and break the loop? 我能否获得一次输出并中断循环?

basically your code is checking one character at time , and if it is matched its printing the whole list in reverse ,try using 基本上,您的代码正在一次检查一个字符,如果与之匹配,则反向打印整个列表,请尝试使用

dna=input("Enter DNA sequnce")
result=[ x for x in dna if x in["A","T","G","C"]]
print "".join(result[::-1])

if you don't want to use list comprehensions then you can use this as well 如果您不想使用列表推导,那么也可以使用它

for i in allowed_char:
    if i in dna:
        print dna[::-1]
        break

You can try sth along the lines of: 您可以按照以下方式尝试……

dna = input("Enter DNA sequnce") 
print(''.join(x for x in dna[::-1] if x in "ATGC"))
# CTGA -> AGTC
# ABCD -> CA

How about trying something functional programming tricks? 尝试一些函数式编程技巧如何? Here I recommend the PyFunctional lib to do DNA stuff, cause PyFunctional seems to be born with handling sequence problems, hoping you can benefit from it. 在这里,我建议使用PyFunctional库来处理DNA,因为PyFunctional似乎天生就有处理序列问题的方法,希望您能从中受益。

to install functional 安装功能

pip install PyFunctional

For your case, the code looks like: 对于您的情况,代码如下所示:

from functional import seq
from operator import add

data = 'ATGC'

result = (seq(list(data))
          .filter(lambda x: x in {"A", "T", "G", "C"})
          .reduce(add))[::-1]

# CGTA
print(result)

From above, we can see we avoid the for-loop, and use functional programming teches like filter, but we go further by combining the method into a pipline chain, to avoid nested functional methods(something like map(list(filter())) ) 从上面可以看出,我们避免了for循环,并使用了像filter这样的函数式编程技术,但通过将方法组合到一条点线链中,可以进一步避免嵌套函数式方法(诸如map(list(filter())之类的方法) ))

BTW: using x in["A","T","G","C"] is quite slow, instead you should use x in {"A","T","G","C"} which can take advantage of the hash set. 顺便说一句:使用x in [“ A”,“ T”,“ G”,“ C”]相当慢,相反,您应该在{“ A”,“ T”,“ G”,“ C”}中使用x可以利用哈希集。

For more info, check PyFunctional on PyPi , or the Github 有关更多信息,请在PyPiGithub上检查PyFunctional。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM