python - 返回 iter 中 lambda 的产量

标签 python python-3.x lambda yield

f=open('C:\\Python33\\text file.txt','r')

for c in iter(lambda: f.read(1),'\n'):
    print(?)

如何打印 lambda: f.read(1) 产生的值?

最佳答案

只需打印c。这就是您从 for 循环中的 iter() 得到的结果。

f=open('C:\\Python33\\text file.txt','r')

for c in iter(lambda: f.read(1),'\n'):
    print(c)

小改进建议,使用with -声明:

with open('C:\\Python33\\text file.txt', 'r') as f:
    for c in iter(lambda: f.read(1), '\n'):
        print(c)

这样您就不必调用f.close()

关于python - 返回 iter 中 lambda 的产量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23218165/

相关文章:

Python 和 C : Is it possible to mix Ctypes and Swig together?

python - 对列表中的值求和(python)

python - 如何将文件逐行读入列表?

python - 如何下载适用于 Python 3.5.1 的 Pygame?

Python:tqdm 进度条停留在 0%

python - 使用 BeautifulSoup 从 html 中仅提取除脚本标签内容之外的文本

c# - Expression.Compile 与 Lambda 的性能,直接调用与虚拟调用

python - 比丘达; nvcc 致命 : Visual Studio configuration file '(null)' could not be found

c++ - 如何在 C++ 中将 lambda 表达式作为参数传递

java - 使用 Java 合并对 Map<String, Map<String, Integer>> 中的数字求和