The question is odds([1, 2, 3, 4, 5, 6]) the output must be [1, 3, 5]. I know its simple in list comprehension, or a small function.
def odds(l):
r = []
for n in l:
if n % 2 == 1:
r.append(n)
return(r)```
or
def odds(l):
return [n for n in l if n % 2 == 1]
but i need the output using lambda function shown below
odds = lambda :
odds = lambda l: [x for x in l if x % 2 == 1]
Without list expression:
odds = lambda l: list(filter(lambda x:x%2==1, l))
But list expressions are the more pythonic solution always.
This stores a lambda function object in ans.
ans = lambda l: [i for i in l if i&1 == 1]
To use the function:
ans([1,2,3,4,5,6,7])
Output:
[1, 3, 5, 7]
odds = lambda _: list(filter(None, map(lambda x: x if x % 2 == 1 else None, _)))
Without using list comprehension I think there is no simpler way.
Related
I want to swap element list by range in python
my code is
List = [1,2,3,4,5,6]
def swap(list_, a, b):
list_[a], list_[b] = list_[b], list_[a]
swap(List, 0, 5,)
print(List)
and my output is
[6, 2, 3, 4, 5, 1]
but what i want is swapped by list index range
# my expected output
n = 2 (add var by input)
#and it swapped to this
[3, 4, 5, 6, 1, 2]
You can use something like this:
def swap(List, n):
return List[n:] + List[:n]
List = [1,2,3,4,5,6]
n = input()
print(swap(List, n))
Using slice (:) you can split your list in sublists by index. Then you can recombine them in the return statement
The request is to rotate a list. When K=3, you turn [1,2,3,4,5,6,7] into [5,6,7,1,2,3,4]; when K=1, you turn [1,2,3,4,5,6,7] into [7,1,2,3,4,5,6]
Why am I out of range?
PyCharm informed me like this: IndexError: list index out of range
class Solution:
def rotate(self, nums, k) -> None:
k = k%len(nums)
def rev(x, y, num):
while y > x:
num[x], num[y] = num[y], num[x]
x += 1
y -= 1
rev(0, len(nums), nums)
rev(0, k-1,nums)
rev(k, len(nums), nums)
nums = [1,2,3,4,5,6,7]
s = Solution()
s.rotate(nums,3)
You have a off by one error as the indexing starts at 0 ends at len(list)-1. You call rev like this:
rev(0, len(nums), nums)
correct would be:
rev(0, len(nums)-1, nums)
Furthermore, due to the ability to add lists and index lists with negative indices in python you can also solve the problem this way:
nums = [1,2,3,4,5,6,7]
def rotate_list(list_to_rotate, k):
return list_to_rotate[-k:] + list_to_rotate[:-k]
rotate_list(nums, 3)
# output: [5, 6, 7, 1, 2, 3, 4]
you're getting an index out of range error because you're trying to access an index in the list that doesn't exist.
Typically, your list nums has 7 elements which means you can do nums[i] if 0<=i<=6.
To fix your code you just need to replace rev(0, len(nums), nums) by rev(0, len(nums)-1, nums)
class Solution:
def rotate(self, nums, k) -> None:
k = k % len(nums)
def rev(x, y, num):
while y > x:
num[x], num[y] = num[y], num[x]
x += 1
y -= 1
rev(0, len(nums)-1, nums)
rev(0, k - 1, nums)
rev(k, len(nums)-1, nums)
nums = [1, 2, 3, 4, 5, 6, 7]
s = Solution()
s.rotate(nums, 3)
Alternatively, you can use this simpler implementation which returns another list:
class Solution:
def rotate(self, nums, k) -> list:
k = k % len(nums)
return nums[-k:] + nums[:-k]
nums = [1, 2, 3, 4, 5, 6, 7]
s = Solution()
nums = s.rotate(nums, 3)
L = [9, 2, 1, 3, 4, 5, 6]
x = str(filter(lambda x: x > 30, map(lambda x: x*x, L)))
I know that in order to remove the or whatever at the output, I can add a list() in front or tuple ().
I know the answer for x is [81, 36], but how do I actually produce it at the output? I cant seem to make it work with list() or tuple()
You are converting it to a str.. remove the str()
x = list(filter(lambda x: x > 30, map(lambda x: x*x, L)))
Converting the filter-object to str will only covert it to str:
x = str(filter(lambda x: x > 30, map(lambda x: x*x, L)))
print(type(x)) # <class 'str'>
What you need is to convert it into list instead of str:
L = [9, 2, 1, 3, 4, 5, 6]
x = list(filter(lambda x: x > 30, map(lambda x: x*x, L)))
OUTPUT:
[81, 36]
filter() is an equivalent of defining a generator with the same behavior, not a list. Generators have the property of generating the values not until you call the generator's __next__() member function, what is essentially what happens during iteration.
As other answers stated, you can convert a generator to a list using list() (see here for example), but be aware that generators are one-time-use objects, and trying to use list() a second time will result in an empty list.
The python docs say
Note that filter(function, iterable) is equivalent to the generator expression (item for item in iterable if function(item)) if function is not None and (item for item in iterable if item) if function is None.
I have 2 lists:
a=[0,2,0,5]
b=[3,4,5,6]
I want to find remove all the 0 from list a and remove corresponding values(with same index) in list b.
My result should be:
a=[2,5]
b=[4,6]
until now I did:
a = [idx for idx, val in enumerate(a) if val == 0]
and get a=[1,3]
but I don't manage to get the corresponding list in b
a=[0,2,0,5]
b=[3,4,5,6]
a, b = map(list, zip(*[[i, j] for i, j in zip(a, b) if i != 0]))
print(a)
print(b)
Prints:
[2, 5]
[4, 6]
You got a list indexes correctly, to get valid elements from b list the easy way is to do
[b[idx] for idx, val in enumerate(a) if val != 0]
and to get a values
[val for val in a if val != 0]
to do it in one iteration:
x = [(val, b[idx]) for idx, val in enumerate(a) if val != 0]
or
x = [(val_a, val_b) for val_a, val_b in zip(a, b) if val_a != 0]
but it gives you list of tuples, but you can use some python magic to turn it into two lists
a, b = map(list, zip(*x))
I have three identical length lists for scatter plotting: x (float), y (float) and c (integer for colour), and would like to split up the x and y lists into subsets filtered by the colour value so that I can use a legend the delineate them in a plot
While I could achieve this with len(c) loops over the x and y lists, it is not very pythonic, and I was hoping someone could provide something a bit more elegant
I was thinking something like the following, but it's clearly not working
c_list = list(set(c))
xset = []
yset = []
for j in c_list:
xset.append([i for i in x if j in c])
yset.append([i for i in y if j in c])
Be gentle - I've only been learning Python for a week or so!
Thanks in advance
I hope this helps:
x = [1, 2, 3, 4, 5]
y = [5, 3, 1, 3, 2]
c = [1, 3, 2, 3, 1]
c_list = list(set(c))
xset = []
yset = []
for j in c_list:
xset.append([x[i] for i, v in enumerate(c) if v == j])
yset.append([y[i] for i, v in enumerate(c) if v == j])
print(xset)
print(yset)