** Notes on Effective Python ** Item 8: Avoid more than one expression in list comprehensions (p16-18)
#Output the contents of the matrix to one list
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [x for row in matrix for x in row]
print(flat)
>>>
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Convenient! Let's do a little complicated processing
#Leave the procession and square all the contents
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
squared = [[x ** 2 for x in row] for row in matrix]
print(squared)
>>>
[[1, 4, 9], [16, 25, 36], [49, 64, 81]]
Yeah, it's a little complicated but still readable Let's add another loop!
#Output the contents of a 3D matrix into a single list
my_list = [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]
flat = [x for sublist1 in my_list for sublist2 in sublist1 for x in sublist2]
print(flat)
>>>
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
It became very hard to see. At this point, there is almost no merit of inclusion notation. Let's write with a normal for statement
#Write in a normal for loop
my_list = [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]
flat = []
for sublist1 in my_list:
for sublist2 in sublist1:
flat.extend(sublist2) #It's not append!
print(flat)
>>>
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
This will have longer lines, but it will be more readable than the previous description. The most important thing is readability rather than the number of lines!
Recommended Posts