Skip to content Skip to sidebar Skip to footer

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 a

Solution 1:

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]

Solution 2:

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


Post a Comment for "Variable Size Array Matching"