我的要求是让我更熟悉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>]
非常感谢你的努力和你的方法
地图需要一个索引。您给map的lambda对iterable中的每一行运行一次,但每次只运行一次。所以在lambda中,
x
总是一行,而不是全部。因此,在x
上调用splitlines
,或者跨x
枚举(只有一个部分)没有多大意义相反,完全不要使用
map
,只要在拆分行之后跨行枚举:相关问题 更多 >
编程相关推荐