I have a data file which 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 items, say seen = [4 8 5] that I want to search in the above array. Since some of the rows have less than three columns, the following code fails to 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 the rows that have less than three columns?
Using slice, you don't need to check all 3 items manually and check length:
take = [row for row in lines if row[:3] == seen]
Add a 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 check if the row doesn't have enough elements
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With