I try to print from a list, only the organs that match the condition (divided by 2) with the help of a Lambda and something here does not work:
list = list(range(0, 50))
[(lambda x: print(x) if(x % 2 == 0)(x(l)) for l in list]
No need for a lambda for this task, you can just use a list comprehension to generate the sub-list of elements matching the condition:
l = list(range(0, 50))
print([x for x in l if x % 2 == 0])
check it
x = [i for i in range(50) if not i %2]
You don't need to use lambda for this. You can do this way:
list = list(range(50))
[i for i in list if i%2==0]
Related
Let's say I have the following list of lists:
final_list = [[1,'pppizza',3,4],[1,'mmmonkey',9,10],[1,'dddoublerainbow',8,2]]
Now I need to remove the first 2 characters of the second element of every list, so the result will be:
final_list = [[1,'pizza',3,4],[1,'monkey',9,10],[1,'doublerainbow',8,2]]
No need to rebuild the entire list from scratch just to do it in a one-line comprehension while unnecessarily iterating the inner lists. Just modify the elements that need modifying:
for lst in final_list:
lst[1] = lst[1][2:]
use double list comprehensions:
final_list = [[x if hasattr(x, '__len__') and i == 1 else x[2:] for i, x in enumerate(y)] for y in my_list]
this will trim the first 2 elements of the second element, even if the element is not a string
If you want it for strings only then the statement becomes:
final_list = [[x if type(x) == str and i == 1 else x[2:] for i, x in enumerate(y)] for y in my_list]
final_list = [[x[2:] if i==1 else x for i, x in enumerate(y)] for y in my_list]
Full answer:
final_list = []
for y in my_list:
l = []
for i, x in enumerate(my_list):
if i==1: #2nd element in the list
l.append(x[2:]) # Append a string starting from the 3rd letter to the end
else:
l.append(x) . # Just append the element at x
my_list.append(l) # Append the list l to my_list
print(my_list)
I have two lists of the same length.
The first one contains strings. The second one - strings that can be either 'True' or 'False'.
If the nth element of the second list is 'True', I want to append the nth element of the first list to another list.
So if I have:
List1:
('sth1','sth2','sth3','sth4')
List2:
('True','False','True','False')
The outcome should be List3:
('sth1','sth3').
How can I intersect two list in that way?
Use zip:
result = [x for x, y in zip(xs, ys) if y == 'True']
Example:
xs = ('sth1','sth2','sth3','sth4')
ys = ('True','False','True','False')
result = [x for x, y in zip(xs, ys) if y == 'True']
result
['sth1', 'sth3']
Or use numpy:
import numpy as np
filtered = np.array(List1)[np.array(List2)]
Btw this only works if the elements inside List2 are True/False, not if they are "True"/"False".
If you didn't know about zip :
l1 = ('sth1','sth2','sth3','sth4')
l2 = ('True','False','True','False')
l = [x for i,x in enumerate(l1) if l2[i]=='True']
print l
#=> ['sth1', 'sth3']
It would be shorter with a tuple of booleans :
l1 = ('sth1','sth2','sth3','sth4')
l2 = (True,False,True,False)
l = [x for i,x in enumerate(l1) if l2[i]]
print l
Simplest way is to use itertools.compress method as follows.
import itertools
list1 = ('sth1','sth2','sth3','sth4')
list2 = ('True','False','True','False')
list2 = map(lambda x: x == 'True', list2)
result = list(itertools.compress(list1, list2))
compress method returns an iterator, so you that is why you need to wrap the iterator object in list
I hope it helps.
def divisble_numbers(a_list, terms):
b_list = [x for x in [a_list] if (x % [terms] == 0)]
c_list = [x for x in b_list if all(x % [terms] == 0)]
return c_list
divisble_numbers([2,3,5,1,6,7,8,9,10,11,12], [2,3])
Returns this error: TypeError: unsupported operand type(s) for %: 'int' and 'list'
I am trying to get to get a list of the index that is divisible by both terms. I am confused on the error I am getting, very new to list comprehension would appreciate any help.
You were pretty close. This code should work:
def divisble_numbers(a_list, terms):
return [x for x in a_list if all(x % term == 0 for term in terms)]
print(divisble_numbers([2,3,5,1,6,7,8,9,10,11,12], [2,3]))
# Output:
# [6, 12]
There are two list comprehensions happening here. One is x for x in a_list if .... The other one is inside the all: x % term == 0 for term in terms.
Your list comprehensions are good, but you've accidentally wrapped a few things in square brackets, such as [terms], which don't need to be because they are already lists. [terms] will produce a list containing a list.
Second, the error that you were getting is because you were taking the mod (%) of a list. The mod operator only works between numbers.
def divisble_numbers(a_list, terms):
b_list = [x for x in a_list if (x % terms[0] == 0)]
c_list = [x for x in b_list if (x % terms[1] == 0)]
return c_list
b_list = [x for x in a_list if x%(reduce(lambda x,y : x*y, terms))==0]
Input :
a_list, terms = [2,3,5,1,6,7,8,9,10,11,12], [2,3]
Output :
[6, 12]
Your function will be :
def divisble_numbers(a_list, terms): return [x for x in a_list if x%(reduce(lambda x,y : x*y, terms))==0]
I need to create a function that takes a list of words and then I want to check all the strings in that list and return another list of strings where the string first and last character are the same.
For example, given input_list = ['a','aa','aba','abb'] output should be ['aa','aba'].
Try the following:
def myfunc(lst):
return [item for item in lst if len(item) > 1 and item[0] == item[-1]]
>>> myfunc(['a','aa','aba','abb'])
['aa', 'aba']
>>>
Just check the length is > 1, and see if the first char x[0] is equal to the last char x[-1]:
print(list(filter(lambda x: len(x) > 1 and x[0] == x[-1], lst)))
['aa', 'aba']
Or if you want a function:
f = lambda l:list(filter(lambda x: len(x) > 1 and x[0] == x[-1], l))
print(f(lst))
The way to approach this, typically, is filtering a list, instead of seeing it as a different one, and define any function (either regular or lambda) to express what needs to be filtered on. That way your code is clear and easy to test and maintain:
filteredList = filter(lambda x: len(x) > 1 and x[0] == x[-1], myList)
#or:
def starts_and_ends_with_same_char(subject):
return len(subject) > 1 and str[0] == subject[-1]
filteredList = filter(starts_and_ends_with_same_char, myList)
Golfing a little:
>>> [s for s in lst if s[1:] and s[0] == s[-1]]
['aa', 'aba']
Lets say I have a list of tuples as follows
l = [(4,1), (5,1), (3,2), (7,1), (6,0)]
I would like to iterate over the items where the 2nd element in the tuple is 1?
I can do it using an if condition in the loop, but I was hoping there will a be amore pythonic way of doing it?
Thanks
You can use a list comprehension:
[ x for x in l if x[1] == 1 ]
You can iterate over tuples using generator syntax as well:
for tup in ( x for x in l if x[1] == 1 ):
...
How about
ones = [(x, y) for x, y in l if y == 1]
or
ones = filter(lambda x: x[1] == 1, l)
Just use the if. It's clear and simple.
for x, y in tuples:
if y == 1:
do_whatever_with(x)
Build a generator over it:
has_1 = (tup for tup in l if l[1] == 1)
for item in has_1:
pass
for e in filter(l, lambda x: x[1] == 1):
print e
Try this, using list comprehensions is the pythonic way to solve the problem:
lst = [(4,1), (5,1), (3,2), (7,1), (6,0)]
[(x, y) for x, y in lst if y == 1]
=> [(4, 1), (5, 1), (7, 1)]
Notice how we use tuple unpacking x, y to obtain each of the elements in the pair, and how the condition if y == 1 filters out only those element with value 1 in the second element of the pair. After that, you can do anything you want with the elements found, in particular, I'm reconstructing the original pair in this part at the left: (x, y)
Since you want to iterate, itertools.ifilter is a nice solution:
from itertools import ifilter
iter = ifilter(lambda x: x[1] == 1, l)
for item in iter:
pass