生成器表达式格式不正确?蟒蛇

时间:2015-07-07 17:44:03

标签: python printing generator generator-expression

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

所以我的ifelse声明就是这个......

sequence = 'CTGAGTAGC'
reference = 'ATGACTGCC'

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

我已经尝试过if 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

2 个答案:

答案 0 :(得分: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')

答案 1 :(得分:0)

    <td>
      <div class="currencyLabel-readonly" ng-cloak>
       {{bridgeModel.bridges[currentIndex].aestheticsOverride == 0 ? bridgeModel.bridges[currentIndex].aestheticsCalculated: bridgeModel.bridges[currentIndex].aestheticsOverride}}
      </div>&nbsp;&nbsp;(B)
    </td>

在这种类型的陈述中,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 是一个python三元表达式(采用"-".join(i) if i[0] == i[1] else " ".join(i)形式)