radouxju
radouxju

Reputation: 193

finding a list in a list of list based on one element

I have a list of lists representing a connectivity graph in Python. This list look like a n*2 matrix

example = [[1, 2], [1, 5], [1, 8], [2, 1], [2, 9], [2,5] ]

what I want to do is to find the value of the first elements of the lists where the second element is equal to a user defined value. For instance :

in Matlab, I could use

output = example(example(:,1)==input, 2);

but I would like to do this in Python (in the most pythonic and efficient way)

Upvotes: 0

Views: 70

Answers (3)

Oni1
Oni1

Reputation: 1505

You can work with the Python functions map and filter very comfortable:

>>> example = [[1, 2], [1, 5], [1, 8], [2, 1], [2, 9], [2,5] ]
>>> n = 5
>>> map(lambda x: x[0], filter(lambda x: n in x, example))
[1,2]

With lambda you can define anonyme functions... Syntax:

lambda arg0,arg1...: e

arg0,arg1... are your parameters of the fucntion, and e is the expression. They use lambda functions mostly in functions like map, reduce, filter etc.

Upvotes: 1

mounaim
mounaim

Reputation: 1180

exemple = [[1, 2], [1, 5], [1, 8], [2, 1], [2, 9], [2,5] ]
foundElements = []
** input = [...] *** List of Inputs
for item in exemple:
    if item[1] in input :
        foundElements.append(item[0])

Upvotes: 0

thefourtheye
thefourtheye

Reputation: 239473

You can use list comprehension as a filter, like this

>>> example = [[1, 2], [1, 5], [1, 8], [2, 1], [2, 9], [2,5]]
>>> n = 5
>>> [first for first, second in example if second == n]
[1, 2]

Upvotes: 2

Related Questions