我想使用map()、lambda和enum的组合

2024-04-20 09:05:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我的要求是让我更熟悉lambda的功能:map()、lambda、enumerate()和list()的组合

我不想在这个阶段使用列表理解或其他功能

filename = "Bibel.txt"
file = open(filename, mode="r", encoding="latin-1")

bibel_string = file.read()
bibel_list = file.readlines()

file.close()

# that works fine and generates the desired output
list(enumerate(bibel_string.splitlines()[:50], start=1))

# Attempt that does not run as desired
list(map(lambda x: enumerate(x.splitlines(), start=1), bibel_string))[:5]

# Output of attempt
[<enumerate at 0x1969a34b0>,
 <enumerate at 0x1969a35f0>,
 <enumerate at 0x1969a3640>,
 <enumerate at 0x1969a35a0>,
 <enumerate at 0x1969a36e0>]

非常感谢你的努力和你的方法


Tags: lambda功能mapstringthatfilename阶段start
1条回答
网友
1楼 · 发布于 2024-04-20 09:05:04

地图需要一个索引。您给map的lambda对iterable中的每一行运行一次,但每次只运行一次。所以在lambda中,x总是一行,而不是全部。因此,在x上调用splitlines,或者跨x枚举(只有一个部分)没有多大意义

相反,完全不要使用map,只要在拆分行之后跨行枚举:

list(enumerate(bibel_string.splitlines()))

相关问题 更多 >