How do I use itertools.groupby()?

前端 未结 13 2040
失恋的感觉
失恋的感觉 2020-11-22 02:14

I haven\'t been able to find an understandable explanation of how to actually use Python\'s itertools.groupby() function. What I\'m trying to do is this:

<
13条回答
  •  忘掉有多难
    2020-11-22 02:25

    This basic implementation helped me understand this function. Hope it helps others as well:

    arr = [(1, "A"), (1, "B"), (1, "C"), (2, "D"), (2, "E"), (3, "F")]
    
    for k,g in groupby(arr, lambda x: x[0]):
        print("--", k, "--")
        for tup in g:
            print(tup[1])  # tup[0] == k
    
    -- 1 --
    A
    B
    C
    -- 2 --
    D
    E
    -- 3 --
    F
    

提交回复
热议问题