开发者

the right expression for ["A" for x in range(0,10) or "B" if x == 9] in python?

I want to express x is in range(0,10), if x == 9 then "B", else "A", what开发者_StackOverflow中文版 is the right expression for that with in a line? Thanks!

["A" for x in range(0,10) if x == 9 or "B"]    # wrong
["A" for x in range(0,10) or "B" if x == 9]    # wrong


Try this:

["A" if x == 9 else "B" for x in range(0,10)] 


Alternatively:

>>> ['A']*9+['B']
['A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B']


Another option:

>>> d = {9:"B"}
>>> [d.get(n, "A") for n in range(10)]
['A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B']

This is a bit more useful if you have several B values to insert.


['B' if x==9 else 'A' for x in range (0,10)]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜