Mapping variable dimensions
I have a data file that is sorted based on the first column
1 3 2
3 6
4 8 5 6 2
4 9
5 2 2
There is a key with three elements, for example seen = [4 8 5]
, which I want to find in the above array. Since some of the rows have less than three columns, the following code does not compare and I know that
take = [row for row in lines if row[0] == seen[0] and row[1] == seen[1] and row[2] == seen[2]]
So what should I do for rows with three columns?
+3
mahmood
source
to share
2 answers
By using a slice, you don't have to manually check all 3 elements and check the length:
take = [row for row in lines if row[:3] == seen]
+3
falsetru
source
to share
Add guard ( len(row) >= 3
):
take = [row for row in lines if len(row) >= 3 and row[0] == seen[0] and row[1] == seen[1] and row[2] == seen[2]]
This will short-circuit (and fail) the validation if the string does not have enough elements
+1
Reut sharabani
source
to share