简体   繁体   English

python all()遍历字符串

[英]python all() iterate through a string

I would like to iterate through a string and make sure that the string only consists of these letters: 'A','C','G','T' 我想遍历字符串,并确保该字符串仅包含以下字母:'A','C','G','T'

>>>string = 'm'
>>>nucleotide = ('A','C','G','T')
>>>print(all(nucleotide for i in string))

This is what I entered, but it comes out to be true in the output. 这是我输入的内容,但在输出中显示为真实。 Why is that? 这是为什么?

You are testing if nucleotide is not empty; 您正在测试nucleotide是否不为空; you never test i against it. 你永远不会测试i反对它。

You'd have to use in to actually see if i is in the tuple: 您必须使用in才能真正查看i是否在元组中:

all(i in nucleotide for i in string)

It'd be more efficient to make nucleotide a set: nucleotide设为一组会更有效:

nucleotide = {'A', 'C', 'G', 'T'}

More efficient still is to use a regular expression, at which point the whole test is done in C code: 仍然更有效的方法是使用正则表达式,此时,整个测试都在C代码中完成:

import re

dna_bases = re.compile(r'^[ACGT]+$')

print(dna_bases.fullmatch(string) is not None)  # Python 3.4, use .match for earlier versions.

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

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