-1

我正在尝试将几个ifelse语句更改为生成器表达式,并且由于某种原因它给了我一个错误。

所以我的ifelse声明是这样的..

sequence = 'CTGAGTAGC'
reference = 'ATGACTGCC'

for seq, ref in zip(sequence,reference):
    if seq == ref:
        print seq,'-',ref
    else:
        print seq,' ',ref

我已经在这个生成器表达式中尝试了上面的 if 和 else 语句..

tmp = (seq,'-',ref if seq==ref else seq,' ',ref for seq,ref in zip(sequence,reference))
print tmp

它给了我这样的错误:

tmp = (seq,'-',ref if seq==ref else seq,' ',ref for seq,ref in zip(sequence,reference))
                                                  ^
SyntaxError: invalid syntax
4

2 回答 2

2

您需要消除表达式中的元组的歧义:

tmp = ((seq, '-', ref) if seq == ref else (seq, ' ', ref)
       for seq, ref in zip(sequence, reference))

甚至

tmp = ((seq, '-' if seq == ref else ' ', ref)
       for seq, ref in zip(sequence, reference))

演示:

>>> sequence = 'CTGAGTAGC'
>>> reference = 'ATGACTGCC'
>>> tmp = ((seq, '-' if seq == ref else ' ', ref)
...        for seq, ref in zip(sequence, reference))
>>> for tup in tmp:
...     print tup
... 
('C', ' ', 'A')
('T', '-', 'T')
('G', '-', 'G')
('A', '-', 'A')
('G', ' ', 'C')
('T', '-', 'T')
('A', ' ', 'G')
('G', ' ', 'C')
('C', '-', 'C')
于 2015-07-07T17:45:23.943 回答
0
print seq,'-',ref

在这种类型的声明中,print是为您将字符串放在一起。seq, '-', ref其他任何地方都是元组,如果你不想要一个元组......

tmp = ( "-".join(i) if i[0] == i[1] else " ".join(i) for i in zip(sequence,reference))

for i in tmp:
    print i

"-".join(i) if i[0] == i[1] else " ".join(i)是一个 python 三元表达式(它的形式是A if condition else B

于 2015-07-07T18:03:26.273 回答