You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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_string is a full text string. When you pass it to map(), map iterates over individual characters in the string (not lines!). So each x in 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), and enumerate() 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:

  1. bibel_string.splitlines()[:50]: Splits the full text into a list of lines, then grabs the first 50 lines.
  2. enumerate(..., start=1): Attaches a line number (starting at 1) to each line, producing an iterator of (line_number, line_text) tuples.
  3. map(lambda item: item, ...): Applies a lambda that simply returns each tuple (this fulfills your requirement to use lambda—if you wanted to modify the line text (e.g., uppercase it), you could do that here: lambda item: (item[0], item[1].upper())).
  4. list(): Converts the iterator from map() 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:23:23