Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map 2 lists with comparison in python

Tags:

python

map

I have a list of objects of say foos. I have a loop for creating a new list.

foo1 = {id:1,location:2}
for e.g. foos = [foo1,foo2,foo3]

Now I want to create a new list based on location.

new_list = []
for foo in foos:
  if foo.location==2:
      new_list.append(foo)

What I want to know is there any way in which I can do something like this

new_list = []
new_list = map(if foo.location ==2,foos) // this is wrong code but is something like this possible. ?

Can I use map function here ? if yes how ?

like image 546
Akash Deshpande Avatar asked Dec 25 '12 19:12

Akash Deshpande


People also ask

How do I map two different lists in Python?

The sum() function is used to add two lists using the index number of the list elements grouped by the zip() function. A zip() function is used in the sum() function to group list elements using index-wise lists. Let's consider a program to add the list elements using the zip function and sum function in Python.

Can 2 lists be compared in Python?

We can club the Python sort() method with the == operator to compare two lists. Python sort() method is used to sort the input lists with a purpose that if the two input lists are equal, then the elements would reside at the same index positions.

How do I compare two lists to find differences in Python?

The difference between two lists (say list1 and list2) can be found using the following simple function. By Using the above function, the difference can be found using diff(temp2, temp1) or diff(temp1, temp2) . Both will give the result ['Four', 'Three'] .


2 Answers

Sure thing you can do it with function. You can use the filter builtin function:

new_list = filter(lambda foo: foo.location == 2, foos)

But the more general and "pythonic" way is to use list comprehensions

new_list = [foo for foo in foos if foo.location == 2]
like image 175
cleg Avatar answered Oct 09 '22 18:10

cleg


List comprehension seems to be what you want to use:

new_list = [foo for foo in foos if foo.location == 2]

map is good when you want to apply a function to every item in a list (or any iterable) and get a list of equal length (or an iterator in Python3) as a result. It can't "skip" items based on some condition.

like image 45
Lev Levitsky Avatar answered Oct 09 '22 17:10

Lev Levitsky