python - 如何对列表项使用 sum() ?

标签 python text-files

我正在尝试创建一个程序来打印文件中某些值的平均值。当我使用文件“cropdata.txt”运行代码时,其中包含以下内容:

Lettuce 1 2 3 
Tomato 6 5 1 

我收到以下错误:

    line_mean = (sum(line_parts[1:])/len(line_parts))
TypeError: unsupported operand type(s) for +: 'int' and 'str' 

我不太确定为什么会这样,因为我认为我已将所选元素转换为整数。

我的代码:

file = ('cropdata.txt')
with open(file, 'r') as file_numsort_1:
    for line in file_numsort_1:
        line = (line.rstrip(" \n"))
        line_parts = line.split(' ')
        for num in line_parts[1:]:
            num=int(num)
        line_mean = (sum(line_parts[1:])/len(line_parts))
        print(line_mean) 

最佳答案

像这样num=int(num)进行转换后,您没有将转换保存回列表中。
尝试像这样转换:

line_parts = [int(x) for x in line_parts[1:]]

然后像这样求和:

line_mean = (sum(line_parts)/len(line_parts))

或者您可以使用 statistics模块而不是自己求和。

<小时/>

优化版本:

import statistics

file = ('cropdata.txt')
with open(file, 'r') as file_numsort_1:
    for line in file_numsort_1:
        # Strip, split, and convert to int
        line_ints = map(int, line.rstrip().split()[1:])

        # Print the mean
        print(statistics.mean(line_ints)) 

关于python - 如何对列表项使用 sum() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36632289/

相关文章:

python - 尝试加入两个 pandas 数据帧但得到 "ValueError: You are trying to merge on object and int64 columns."?

python - 从文本文件编码表情符号(Python)的最佳和干净的方法

powershell - 如何从文本文件中提取特定行

string - 使用vbscript将汉字写入文本文件

python - Tensorflow 0.7.1 与 Cuda 工具包 7.5 和 cuDNN 7.0

Python - 列表理解与测试以避免被零除

python - 为什么 gethostbyaddr(gethostname()) 返回我的 IPv6 IP?

php - 如何使用 PHP 从文本文件(数组)中选择一个随机单词?

java - 在 BufferedWriter.write() 中替换\n?

python内存分配跟踪