arilwan
arilwan

Reputation: 3973

Filtering array of arrays

I am having this array of arrays containing locations and time information:

my_array[:5]
[['39.921712' '116.472343' '0' '13' '39298.1462037037' '2007-08-04' '03:30:32']
 ['42.161385' '123.660773' '0' '221' '39298.6697337963' '2007-08-04' '16:04:25']
 ['42.161755' '123.66135' '0' '221' '39298.6697569444' '2007-08-04' '16:04:27']
 ['42.16194' '123.661638' '0' '221' '39298.6697685185' '2007-08-04' '16:04:28']
 ['39.907285' '116.448303' '0' '98' '39298.1581134259' '2007-08-04' '03:47:41']]

The first and second elements of each array are the position´s latitude and longitude.

I want to filter my_array to contain only those arrays where the latitude falls between 39.45 - 40.05 and the longitude fall between 115.416 - 117.5.

Expected out:

my_array_sorted
[['39.921712' '116.472343' '0' '13' '39298.1462037037' '2007-08-04' '03:30:32']
 ['39.907285' '116.448303' '0' '98' '39298.1581134259' '2007-08-04' '03:47:41']]

Upvotes: 1

Views: 959

Answers (2)

bherbruck
bherbruck

Reputation: 2226

You can do this with a list comprehension:

data = [['39.921712', '116.472343', '0', '13', '39298.1462037037', '2007-08-04', '03:30:32'],
 ['42.161385', '123.660773', '0', '221', '39298.6697337963', '2007-08-04', '16:04:25'],
 ['42.161755', '123.66135', '0', '221', '39298.6697569444', '2007-08-04', '16:04:27'],
 ['42.16194', '123.661638', '0', '221', '39298.6697685185', '2007-08-04', '16:04:28'],
 ['39.907285', '116.448303', '0', '98', '39298.1581134259', '2007-08-04', '03:47:41'],]

filtered = [i for i in data
            if 39.45 < float(i[0]) < 40.05
            and 115.416 < float(i[1]) < 117.5]

print(filtered)

Output:

[['39.921712', '116.472343', '0', '13', '39298.1462037037', '2007-08-04', '03:30:32'],
['39.907285', '116.448303', '0', '98', '39298.1581134259', '2007-08-04', '03:47:41']]

Upvotes: 2

No&#233; Mastrorillo
No&#233; Mastrorillo

Reputation: 309

You should look at python's filter method that takes a predicate and your list, and keep only the elements that complete the predicate.

Here is an example taken from the documentation above:

number_list = range(-5, 5)
less_than_zero = list(filter(lambda x: x < 0, number_list))
print(less_than_zero)

# Output: [-5, -4, -3, -2, -1]

In your case it should looks like this:

my_array_sorted = list(filter(lambda array: 39.45 < array[0] < 40.05 and 115.416 < array[1] < 117.5))

Upvotes: 1

Related Questions