Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何选择for循环的最后一个元素?_Python_Python 3.x - Fatal编程技术网

Python 如何选择for循环的最后一个元素?

Python 如何选择for循环的最后一个元素?,python,python-3.x,Python,Python 3.x,所以这段代码输出的数字是78,也就是文本文件中的字数,如何得到“78”而只有“78”?所以我可以自己使用,提前谢谢 f = open("unknown.txt", 'r') a = sum(line.count('ly') for line in f) f = open("unknown.txt", 'r') words = 0 for line in f: words += len(line.split()) print(words) 这将打印文件中每行后面的总字数。如果

所以这段代码输出的数字是78,也就是文本文件中的字数,如何得到“78”而只有“78”?所以我可以自己使用,提前谢谢

f = open("unknown.txt", 'r')
a = sum(line.count('ly') for line in f)

f = open("unknown.txt", 'r')
words = 0

for line in f:
    words += len(line.split())
    print(words)
这将打印文件中每行后面的总字数。如果您只想在python计算出字数后打印字数,请缩进
print
调用:

for line in f:
    words += len(line.split())
    print(words)

听起来像是要计算文件中的字数

最好的方法是使用内置的
len
功能

for line in f:
    words += len(line.split())

print(words)

要处理较大的文件,应通过迭代(生成器)完成,以下是一个函数:

with open(file_path) as f:
    words = len(f.read().split())
def words_in_file(file_path):
    with open(file_path) as f:
        return sum(len(line.split()) for line in f)
使用该功能:

with open(file_path) as f:
    words = len(f.read().split())
def words_in_file(file_path):
    with open(file_path) as f:
        return sum(len(line.split()) for line in f)

变量
words
中有
78
?请尝试将打印调用移出for循环。请注意,如果文件太大,则可能会出现问题,因为它必须将所有文件读取到内存中。在这种情况下(公认罕见),逐行加起来可能更好。@Lattyware太真实了-编辑后无法反映。