python - 无法返回我想要的列表

标签 python python-3.x

我有一段代码可以正常工作,但我不想一个接一个地打印结果,而是想将它们附加到列表中并返回列表。我尝试了所有我能想到的但都失败了。请帮忙。

def calc_averages():

    allprices = [ ['','','', '' ,1.0 ,2.0 ,1.2 ,1.3 ,1.1 , '', '',''],\
              ['','','' ,1.2 ,1.0 ,2.0 ,1.2 ,1.3 ,1.1 , '', '', ''],\
              ['','','' ,1.2, '' ,1.8 ,1.3 ,1.1 , '', '', '', ''],\
              ['','','', '' ,1.0 ,2.0 ,1.2 ,1.2 , '', '', '', ''],\
              ['','','', '' ,1.0 ,2.0 ,1.1 ,1.2 ,1.4 ,1.8 ,1.9 ,2.2] ]

    averages = []
    for lst in range(0,12):
        counter = 0
        total = 0
        for item in allprices:
            if item[lst] != '':
                total = total + item[lst]
                counter = counter + 1
        if counter == 0:
            print('')
        else:
            print(total/counter)

我想在将值附加到平均值列表后返回平均值列表,但返回为空列表。

最佳答案

您根本没有附加平均值或返回平均值

def calc_averages():

    allprices = [['','','', '' ,1.0 ,2.0 ,1.2 ,1.3 ,1.1 , '', '',''],
              ['','','' ,1.2 ,1.0 ,2.0 ,1.2 ,1.3 ,1.1 , '', '', ''],
              ['','','' ,1.2, '' ,1.8 ,1.3 ,1.1 , '', '', '', ''],
              ['','','', '' ,1.0 ,2.0 ,1.2 ,1.2 , '', '', '', ''],
              ['','','', '' ,1.0 ,2.0 ,1.1 ,1.2 ,1.4 ,1.8 ,1.9 ,2.2]]


    averages = []
    for outer in allprices:
        counter = 0
        total = 0
        for item in outer:
            if item != '':
                total += item
                counter += 1
        if counter == 0:
            print('')
        else:
            averages.append(total/counter)
    return averages

print(calc_averages())

输出

[1.3199999999999998, 1.3, 1.35, 1.35, 1.5750000000000002]

关于python - 无法返回我想要的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35540764/

相关文章:

python - 如何将字符串处理成子列表层?

python-3.x - 使用 matplotlib 自动为散点图指定颜色?

python-3.x - 使用python检查PDF文件是否损坏的最佳方法

python - 如何为 python NLTK 构建翻译语料库?

python - 读取输入直到用户停止

python - 在 Path 上安装 Python 3.9 时安装 Tensorflow?

python - 了解递归函数中内置于变量赋值中的多个递归调用

python - OpenPyXL 为整列设置 number_format

python - 如何制作 while(True) : two loops run at same time in python

Python、 Selenium : Isolate Item From Returned List