Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable size array matching

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?

like image 280
mahmood Avatar asked Jun 10 '26 23:06

mahmood


2 Answers

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]
like image 59
falsetru Avatar answered Jun 12 '26 13:06

falsetru


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

like image 33
Reut Sharabani Avatar answered Jun 12 '26 12:06

Reut Sharabani