简体   繁体   English

Python groupby itertools 方法

[英]Python groupby itertools method

I am new to python programing.I am unable to create the following code:我是 python 编程的新手。我无法创建以下代码:

Define a function even_or_odd, which takes an integer as input and returns the string even and odd, if the given number is even and odd respectively.定义一个 function even_or_odd,它将 integer 作为输入,如果给定的数字分别是偶数和奇数,则返回字符串偶数和奇数。 Categorise the numbers of list n = [10, 14, 16, 22, 9, 3, 37] into two groups namely even and odd based on above defined function.根据上面定义的 function 将列表 n = [10, 14, 16, 22, 9, 3, 37] 的数字分为两组,即偶数和奇数。 Hint: Use groupby method of itertools module.提示:使用 itertools 模块的 groupby 方法。 Iterate over the obtained groupby object and print it's group name and list of elements associated with a group.遍历获得的 groupby object 并打印它的组名和与组关联的元素列表。

I have tried below code:我试过下面的代码:

import itertools
def even_or_odd(n):
    if n%2==0:
        return 'even'
    else:
        return 'odd'
group=[]
uniquekeys=[]
n = [10, 14, 16, 22, 9, 3 , 37]
for k,g in itertools.groupby(n, even_or_odd(n)):
    groups.append(list(g))    
    uniquekeys.append(k)

It is giving "TypeError: unsupported operand type(s) for %: 'list' and 'int' "

When you try to pass itertools.groupby even_or_odd you call it with n .当您尝试通过itertools.groupby even_or_odd时,您使用n调用它。 even_or_odd takes an int , but n is a list. even_or_odd需要一个int ,但n是一个列表。 Just change it to itertools.groupby(n, even_or_odd)只需将其更改为itertools.groupby(n, even_or_odd)
Also you append to groups when I think you mean group .当我认为您的意思是group groups

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM