這是我試圖變成列表理解的代碼:table = ''for index in xrange(256): if index in ords_to_keep: table += chr(index) else: table += replace_with有沒有辦法將else語句添加到此理解中?table = ''.join(chr(index) for index in xrange(15) if index in ords_to_keep)
3 回答

青春有我
TA貢獻1784條經驗 獲得超8個贊
如果您想要的是else您不想過濾列表理解,則希望它遍歷每個值。您可以改用true-value if cond else false-value作為語句,并從最后刪除過濾器:
table = ''.join(chr(index) if index in ords_to_keep else replace_with for index in xrange(15))

慕仙森
TA貢獻1827條經驗 獲得超8個贊
語法a if b else c是Python中的三元運算符,a其條件b為true;否則為c??梢栽诶斫庹Z句中使用:
>>> [a if a else 2 for a in [0,1,0,3]]
[2, 1, 2, 3]
因此,對于您的示例,
table = ''.join(chr(index) if index in ords_to_keep else replace_with
for index in xrange(15))
添加回答
舉報
0/150
提交
取消