Kann jemand bitte die groupby-Operation erklären und die Lambda-Funktion auf this SO post?Lambda-Funktion mit itertools count() und groupby()
key=lambda k, line=count(): next(line) // chunk
import tempfile
from itertools import groupby, count
temp_dir = tempfile.mkdtemp()
def tempfile_split(filename, temp_dir, chunk=4000000):
with open(filename, 'r') as datafile:
# The itertools.groupby() function takes a sequence and a key function,
# and returns an iterator that generates pairs.
# Each pair contains the result of key_function(each item) and
# another iterator containing all the items that shared that key result.
groups = groupby(datafile, key=lambda k, line=count(): next(line) // chunk)
for k, group in groups:
print(key, list(group))
output_name = os.path.normpath(os.path.join(temp_dir + os.sep, "tempfile_%s.tmp" % k))
for line in group:
with open(output_name, 'a') as outfile:
outfile.write(line)
Edit: Es dauerte eine Weile, meinen Kopf um die Lambda-Funktion mit groupby verwendet zu wickeln. Ich glaube nicht, dass ich beide sehr gut verstanden habe.
Martijn erklärte es wirklich gut, aber ich habe eine Follow-up-Frage. Warum wird line=count()
jedes Mal als Argument an die Lambda-Funktion übergeben? Ich habe versucht, die Variable line
zu count()
nur einmal außerhalb der Funktion zuweisen.
line = count()
groups = groupby(datafile, key=lambda k, line: next(line) // chunk)
und es ergab TypeError: <lambda>() missing 1 required positional argument: 'line'
Auch next
auf count()
direkt innerhalb der Lambda-Ausdruck nennen, führte in allen Zeilen in der Eingabedatei gebündelten zusammenkommen, dh ein einzelner Schlüssel durch die groupby
Funktion erzeugt wurde .
groups = groupby(datafile, key=lambda k: next(count()) // chunk)
Ich lerne Python auf eigene Faust, so dass jede Hilfe oder Hinweise auf Referenzmaterialien/PyCon Gespräche sehr geschätzt werden. Alles wirklich!
Vielen Dank. Schätze deine Hilfe! – theguyoverthere