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 ?
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.
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.
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'] .
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]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With