Reputation: 15
Below is my task
I have written the below code : I am getting the error 'str' object is not callable. Actually I am not sure how to use itertool groupby() by getting values from a function. Can someone guide me ?
from itertools import groupby
def even_or_odd(r):
for i in r:
if i%2 == 0:
return "even"
else:
return "odd"
n = [10, 14, 16, 22, 9, 3 , 37]
for key, group in groupby(n, even_or_odd(n)):
if key == even:
print(key, list(group))
else:
print(key, list(group))
Upvotes: 0
Views: 1001
Reputation: 9
groupby is a method calculates the keys for each element present in iterable which means one element from iterable object get evaluate at a time.
as grouping of all the even and odd numbers will not work this way. for every element it will return "even": value or "odd": value so it might return new key every time.
Upvotes: 0
Reputation: 615
here the solution according to the doc https://docs.python.org/3.8/library/itertools.html#itertools.groupby
The key is a function computing a key value for each element
from itertools import groupby
n = [10, 14, 16, 22, 9, 3 , 37]
def even_or_odd(val):
if val%2 == 0:
return "even"
else:
return "odd"
for key, group in groupby(n, even_or_odd):
print(key, list(group))
output :
even [10, 14, 16, 22]
odd [9, 3, 37]
Upvotes: 0