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)]
精彩评论