开发者

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

开发者 https://www.devze.com 2023-03-11 08:54 出处:网络
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!

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

精彩评论

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