When I was solving the ATcoder sample problem, the processing time limit could not be exceeded. I solved it by using the comprehension notation, so I will summarize it so that I do not forget it
[String for variables in list or list]
By writing a conditional expression after the range, it is possible to list only those that apply to the conditional expression.
Example)
//Expected results=>[0,2,4,6,8,10]
l = [i for i in range(11) if i%2 == 0]
print(l)
//[0,2,4,6,8,10]
The conditional expression can be put in the for statement, or the value extracted in the for statement can be multiplied by the conditional expression.
//Expected results=>['Apple','Grapes','Apple','Grapes','Apple','Grapes']
l = ['Apple' if i%2 == 1 else 'Grapes' for i in range(11)]
print(l)
//['Apple', 'Grapes', 'Apple', 'Grapes', 'Apple', 'Grapes']
Basically, when creating a list, use it when you want to make the processing speed faster than using it in append.
Since it can support not only lists but also dictionaries and binary arrays, it can be used for code simplification when processing long arrays, so it should be used.
Recommended Posts