4

我不认为我发现了一个错误,但它对我来说看起来不正常。

from itertools import groupby
from operator import itemgetter
c=[((u'http://www.example.com', u'second_value'), u'one'), 
   ((u'http://www.example.com', u'second_value'), u'two'), 
   ((u'http://www.hello.com', u'second_value'), u'one'), 
   ((u'http://www.example.com', u'second_value'), u'three'), 
   ((u'http://www.hello.com', u'second_value'), u'two')]
b= groupby(c, key=itemgetter(0))
for unique_keys, group in b:
    print unique_keys

产量:

(u'http://www.example.com', u'second_value')
(u'http://www.hello.com', u'second_value')
(u'http://www.example.com', u'second_value')
(u'http://www.hello.com', u'second_value')

有什么解释吗?(我期待只有两个不同的键)。如果有区别,我正在使用 python 2.7.1

4

1 回答 1

3

迭代需要已经排序(在相同的键功能上):

from itertools import groupby
from operator import itemgetter
c=[((u'http://www.example.com', u'second_value'), u'one'), 
   ((u'http://www.example.com', u'second_value'), u'two'), 
   ((u'http://www.hello.com', u'second_value'), u'one'), 
   ((u'http://www.example.com', u'second_value'), u'three'), 
   ((u'http://www.hello.com', u'second_value'), u'two')]
b= groupby(sorted(c,key=itemgetter(0)), key=itemgetter(0))
for unique_keys, group in b:
    print unique_keys

出去:

(u'http://www.example.com', u'second_value')
(u'http://www.hello.com', u'second_value')
于 2013-01-16T09:18:38.463 回答