groupby的结果

时间:2017-03-24 15:36:49

标签: python python-3.x

我是python的新手,通过反复试验来学习基本的东西。我想输入一个字符串,并按字符串的结果显示该组。只是想知道如何做到这一点。我试过下面的一些错误。

输入: -

1223452211

代码: -

from itertools import groupby
print(groupby(input()))

错误: -

<itertools.groupby object at 0x0000000000013980E8>

1 个答案:

答案 0 :(得分:0)

您可以使用groupby对元素进行分组。要使用组,请确保对序列进行排序。 groupby获取已排序的数据,然后将其分解为数字更改的组。例如[1,1,1,3,5,5,5,8]将分为[1,1,1],[3],[5,5,5],[8]组,这些组将分别有一个密钥1,3,5,8。 groupby是一个迭代器,迭代器中的键和组可以使用for循环或next()运算符公开。

以下是我展示如何使用它来对列表中的元素进行分组的情况。

from itertools import groupby
mylist = [1,2,5,3,3,5,1,7,8,8,3]
sorted_list = sorted(mylist)
print sorted_string
for key,group in groupby(sorted_list):
    print "elements in the group with key {}".format(key)
    for thing in group:
        print thing
    print '************'

这将导致

sorted list : [1, 1, 2, 3, 3, 3, 5, 5, 7, 8, 8]

elements in the group with key 1
1
1
************
elements in the group with key 2
2
************
elements in the group with key 3
3
3
3
************
elements in the group with key 5
5
5
************
elements in the group with key 7
7
************
elements in the group with key 8
8
8
***********
相关问题