在简单列表中查找特定字符串

时间:2019-05-16 08:30:52

标签: python list

我是编程新手,我正在尝试编写有关DNA的代码,用户可以在其中输入特定的DNA序列。然后程序必须将输入的DNA转换为特定的氨基酸。

我尝试将用户输入的每个DNA字符串转换为列表,然后使用“输入”功能查看用户输入的哪个DNA与特定氨基酸相对应。我的代码如下:

dna = input("please enter the DNA sequence in CAPS: ")

# a variable called codons to convert the entered DNA sequence into a list of 3 characters per element
codons = [dna[start:start+3] for start in range (0,len(dna),3)]

# we now create an if structure which matches each codon to its appropriate amino acid
if "ATA" or "ATC" or "ATT" in codons:
         print("Isoleucine")

if "CTT" or "CTC" or "CTA" or "CTG" or "TTA" or "TTG" in codons:
        print("Leucine")

if "GTT" or "GTC" or "GTA" or "GTG" in codons:
        print("Valine")

if "TTT" or "TTC" in codons:
        print("Phenylalanine")

if "ATG" in codons:
        print("Methionine")

问题是当我运行代码时,它正在打印大多数密码子类型,而不是特定的氨基酸,例如如果用户输入“ ATA”,它将打印异亮氨酸,亮氨酸,缬氨酸和苯丙氨酸,而不是仅打印异亮氨酸。

2 个答案:

答案 0 :(得分:4)

尝试这样的事情:

if any(i in codons for i in ["ATA" , "ATC", "ATT"]):
    # your prints

而不是写两个ors。

答案 1 :(得分:0)

'in'运算符比'or'具有更高的优先级。 因此,您的表达式等同于

if "ATA" or "ATC" or "ATT" in codons:
==>
if "ATA" or "ATC" or ("ATT" in codons):

其值为“ ATA”。

使用(y中的x)或(y中的z)... 或定义

之类的函数
def any_in(elements, container):
    for element in elements:
        if element in container:
            return True
    return False

并调用它:

if any_in(["ATA", "ATC", "ATT"], codons):
    ...

https://www.programiz.com/python-programming/precedence-associativity