在以下列表数据中:
attri_values = ['gene_id "scaffold_200002.1"', 'gene_version "1"', 'transcript_id "scaffold_200002.1"', 'transcript_version "1"', 'exon_number "2"', 'gene_source "jgi"', 'gene_biotype "protein_coding"', 'transcript_source "jgi"', 'transcript_biotype "protein_coding"', 'exon_id "scaffold_200002.1.exon2"', 'exon_version "1"']
说我想应用条件表达式:
gene_id = [x for x in attri_values if 'gene_id' in x]
# But, when there is not list values with 'gene_id' I would like to return NA (string type) but not an empty list, but I am being unsuccessful
gene_name = [x if 'gene_name' in x else 'NA' for x in attri_values]
print(gene_name) #gives me
['NA', 'NA', 'NA', 'NA', 'NA', 'NA', 'NA', 'NA', 'NA', 'NA', 'NA']
# I only want one 'NA' in string format.
我试着在不同的地方写下其他条件。我还尝试了一些来自stackE的例子但没有成功。
if else in a list comprehension
if/else in Python's list comprehension?
谢谢,
答案 0 :(得分:3)
您应该在变量赋值中使用or
语句。
gene_id = [x for x in attri_values if 'gene_id' in x] or ['NA']
这样,如果您的初始列表推导返回空列表,则转到or
的后半部分,并将列表['NA']
分配给变量gene_id
。