如何用map()、lambda、enumerate()和list()实现文本行枚举?
Fixing Your Lambda + Map + Enumerate Implementation
Let's break down what's going wrong with your code and get it working as expected, while sticking to your requirement of using map(), lambda, enumerate(), and list() (no list comprehensions allowed!).
What's Causing the Unexpected Output?
Your problematic line is:
list(map(lambda x: enumerate(x.splitlines(), start=1), bibel_string))[:5]
Here's the core issue:
bibel_stringis a full text string. When you pass it tomap(),mapiterates over individual characters in the string (not lines!). So eachxin your lambda is a single character (like"B","i", etc.).- Calling
splitlines()on a single character does almost nothing (it returns either an empty list or a list containing just that character), andenumerate()returns an iterator object—not the (line number, line text) tuple you're expecting. That's why you see those<enumerate at 0x...>entries in your output.
The Correct Implementation
We need to adjust the flow to work with lines instead of individual characters, while incorporating all the functions you want to use. Here's how:
filename = "Bibel.txt" file = open(filename, mode="r", encoding="latin-1") bibel_string = file.read() file.close() # Get the first 50 lines, add line numbers, and convert to a list using your required functions result = list(map(lambda item: item, enumerate(bibel_string.splitlines()[:50], start=1))) # Check the first 5 entries print(result[:5])
How This Works:
bibel_string.splitlines()[:50]: Splits the full text into a list of lines, then grabs the first 50 lines.enumerate(..., start=1): Attaches a line number (starting at 1) to each line, producing an iterator of(line_number, line_text)tuples.map(lambda item: item, ...): Applies a lambda that simply returns each tuple (this fulfills your requirement to uselambda—if you wanted to modify the line text (e.g., uppercase it), you could do that here:lambda item: (item[0], item[1].upper())).list(): Converts the iterator frommap()into a concrete list of tuples, which matches your expected output.
A Quick Note on Your Original File Reading
You have an unused line in your initial code:
bibel_list = file.readlines()
This will return an empty list because you already called file.read() (which moves the file pointer to the end of the file). You can safely remove this line unless you adjust the order of file reads.
内容的提问来源于stack exchange,提问作者afrobdeluxe
相关产品推荐
相关产品推荐

