Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.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 2.7 - Fatal编程技术网

Python-一个单for循环,计算以下每行的最大、最小和平均字数,以便进行分析

Python-一个单for循环,计算以下每行的最大、最小和平均字数,以便进行分析,python,python-2.7,Python,Python 2.7,需要帮助!Python新手,已经被困了好几天(因此,我在这里发帖,万不得已!) 我需要找到最大值、最小值(基于字数的最长和最短行)以及每行的平均字数(进入到分析字符串中) 我的问题是,我只能得到每行的字数,但它不准确,因为它只是打印每行的字数,而不是哪一行有最大字数和最小字数 这是我的代码: #!/usr/bin/env python # -*- coding: utf-8 -*- """Task 03""" import re from decimal import * def lexic

需要帮助!Python新手,已经被困了好几天(因此,我在这里发帖,万不得已!)

我需要找到最大值、最小值(基于字数的最长和最短行)以及每行的平均字数(进入到分析字符串中)

我的问题是,我只能得到每行的字数,但它不准确,因为它只是打印每行的字数,而不是哪一行有最大字数和最小字数

这是我的代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Task 03"""

import re
from decimal import *

def lexicographics(to_analyze):
"""


"""
lines=0
num_of_words=0
max_words=0
min_words=0
mostWordsInLine=0

for line in to_analyze.split('\n'):
    lines +=1
    words=line.split()
    if len(words) > mostWordsInLine and len(words) != None:
        mostWordsInLine = len(words)
        num_of_words=len(words)
        max_words=max_words+len(words)
        print num_of_words
print "Decimal({:.1f})".format(Decimal(max_words) / Decimal(lines))
电流输出:

>>> import task_03
>>> task_03.lexicographics('''Don't stop believing,
Hold on to that feeling.''')
3
5
Decimal(4.0)
如你所见^-我得到了正确的字数,但它计算了任何一行的字数,而不是我所需要的

输出应如下所示:

>>> import task_03
>>> task_03.lexicographics('''Don't stop believing,
Hold on to that feeling.''')
(5, 3, Decimal(4.0))
如果我想让它也测量另一个文件中的线

>>> import task_03
>>> import data
>>> task_03.lexicographics(data.SHAKESPEARE)
(12, 5, Decimal('8.14'))

非常感谢任何帮助/提示

告诉您这可能是一个简单的
def

from decimal import Decimal
def f(s):
    lines=list(map(lambda x: len(x.split()),s.splitlines()))
    return (max(lines),min(lines),Decimal(sum(lines))/Decimal(len(lines)))
然后:

是:


如果您是Python新手,我建议您安装3.X。Python 2没有得到2020年及以后的任何支持。谢谢!但这是我的Python课程,教授只想让我们使用Python 2.7x——我试着向同学和教授寻求帮助,但没有回应!但是在这节课之后,我一定会这么做的!:)
print(f("Don't stop believing,\nHold on to that feeling."))
(5, 3, Decimal('4'))