当列表值是字符串时,如何使用列表解析的else?

时间:2017-04-17 20:01:57

标签: python if-statement conditional list-comprehension

在以下列表数据中:

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?

谢谢,

1 个答案:

答案 0 :(得分:3)

您应该在变量赋值中使用or语句。

gene_id = [x for x in attri_values if 'gene_id' in x] or ['NA']

这样,如果您的初始列表推导返回空列表,则转到or的后半部分,并将列表['NA']分配给变量gene_id