I'm studying Python, but I got hooked and got stuck for about an hour. I solved it for the time being, but I can't help but if anyone understands this mechanism, I would be grateful if you could teach me, so I will write it.
The following is a program that mixes Los Angeles and New York players with a combination of player names and blocks and divides them into A block and B block respectively.
groupLeague.py
import itertools
LA = [('Jake', 'B'), ('Elwood', 'A')]
NY = [('James', 'A'), ('Carry', 'B'), ('Steven', 'B')]
data = itertools.chain(LA, NY)
def getSortKey(item):
return item[1]
grp = itertools.groupby(sorted(data, key=getSortKey(data), getSortKey(data))
But when I do this, TypeError: 'itertools.chain' object is not subscriptable Will be played with an error.
I didn't understand it at all, and I was really into it, but when I looked at another sample program and revisited it, it worked. In the last line,
grp = itertools.groupby(sorted(data, key=getSortKey(data)), getSortKey(data))
,
grp = itertools.groupby(sorted(data, key=getSortKey), getSortKey)
And, except for the argument of getSortKey, it worked fine.
The program worked for the time being, but I have no idea about this mechanism. I understand that you can specify a "function that can get a key" in addition to the key value as the second argument "key part" of groupby, but when you specify a function, why do you not have to write an argument? Or is it an error if I write an argument? ?? As far as I can confirm the operation, I think that the first argument "iterable part" (sorted ~) is automatically treated as an argument, but there was no such description in the document.
【reference】 Python documentation itertools --- Iterator generation function for efficient loop execution
The same is true for the sorted function. In the part of key = getSortkey, the argument seems to automatically take the data of the first argument, but I do not understand the mechanism (I did not mention it in the document after all).
【reference】 Python documentation built-in functions sorted
What kind of mechanism is this without taking arguments ...? ?? I looked it up, but I just couldn't figure it out. I'm very sorry that this is a rudimentary question, but if you know it, it would be greatly appreciated if you could teach me.
How can we deal with this kind of tricky specification?
Recommended Posts