当列表值为字符串时,如何将 else 与列表理解一起使用?
How to use else with list comprehension when list values are string?
在以下列表数据中:
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?
谢谢,
您应该在变量赋值中使用 or
语句。
gene_id = [x for x in attri_values if 'gene_id' in x] or ['NA']
这样,如果您的初始列表理解 returns 是一个空列表,您可以继续 or
的后半部分并将列表 ['NA']
分配给变量 gene_id
.
在以下列表数据中:
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?
谢谢,
您应该在变量赋值中使用 or
语句。
gene_id = [x for x in attri_values if 'gene_id' in x] or ['NA']
这样,如果您的初始列表理解 returns 是一个空列表,您可以继续 or
的后半部分并将列表 ['NA']
分配给变量 gene_id
.