2013-01-16 53 views
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(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如果有差别

回答

2

可迭代的需求已经被排序(同一个按键上的功能):

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') 
+0

那好吧。非常感谢,我现在无法提出你的答案,因为我没有> 15的声望。文档页面上没有真正的警告。除了考虑其他语言/库中的大多数其他函数并不需要这些之外,这不是一件好事。 – Bqm

+0

对不起,但斜体伤害。 – georg

+0

@ thg435 - 我会尽量不要过度使用,谢谢编辑。 – root