简体   繁体   中英

Trouble understanding itertools.groupby() in Python

Hello and thanks for looking at my question! I have read on the documentations for python and the top rated question for itertools.groupby( ) in python . But I'm still confused as to how this function actually works. Can someone walk me through the for rank, group in groupby (hand , lambda card: card [1]) iteration? Especially the lambda card: card[1] part. From my understanding it is just returning card[1] but there is no variable with card. Also, for rank, group is it because there are 2 values for each index of hand eg the first card is '3S' hence there is 3 and S for its values? Would there need to have a third variable if the say each index of hand were changed to 3 values? Eg '3SH'? Sorry if this seems like a question that was already answered, I really couldn't understand it even in simple terms...

hand = ['3S', '3D', '3H', '4D']

sorted_hand_by_suit = []
for rank, group in groupby (hand , lambda card: card [1]):
    sorted_hand_by_suit.append(list(group))
return sorted_hand_by_suit

print sorted_hand_by_suit # [['3S'],['3D', '4D'], [3H]]

you could re-write it as

what_to_group = hand
def how_to_group(an_item):
   return an_item[1] 

grouped_objects = groupby(what_to_group,how_to_group)
sorted_hand = []
for object in grouped_objects:
    rank = object[0]
    group = list(object[1])
    sorted_hand.append(group)

Im not sure if that helps you clarify whats goin on or not ...

that said this is much better done as

sorted_hand_by_suite = sorted(hand,key=lambda card:reversed(card))

(although it doesnt quite do the same thing...)

Your example needs some correction. Here I've refactored it:

Given

hand = ["3S", "3D", "3H", "4D"]

pred = lambda x: x[1]
iterable = sorted(hand, key=pred)

Code

[list(grp) for key, grp in groupby(iterable, key=pred)]
# [['3D', '4D'], ['3H'], ['3S']]

Details

To understand this, first print the results of the keys:

[key for key, grp in it.groupby(iterable, key=pred)]
# ['D', 'H', 'S']

Notice, these keys correlate with the groups in the former answer.

The keys of the groupby object are defined by the key parameter, which accepts a function. The lambda function pred = lambda x: x[1] is equivalent to the following regular function:

def pred(x):
    return x[1]

Therefore, as each card of the hand is iterated, index 1 of each string is assigned as the key of a group. In other words, if the card '3D' is next, D becomes the key of a group. All consecutive cards containing D at index 1 will be added to the group.

See also this post on How do I use Python's itertools.groupby() ? .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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