查找从CSV文件Python生成的列表的最小值和最大值 [英] Finding Min and Max of list generated from CSV file Python

查看:703
本文介绍了查找从CSV文件Python生成的列表的最小值和最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查找CSV文件每一行的MIN和MAX值,并将它们附加到列表中的下一个位置,即位置5和6.并以最高到最低的顺序输出,但是,我正在努力找出如何找到每一行的MAX和MIN值,以便可以执行相同的操作-从最高到最低.原始CSV的格式为:Fred,56,78,99,每个用户都换行.

I am trying to find the MIN and MAX values for each row of a CSV file and append them to the next position in the list, positions 5 and 6. I have managed to calculate the average, append this to the forth position and output this in highest to lowest however, I am struggling to work out how to find the MAX and MIN values of each row so I can do the same - highest to lowest. The original CSV is formatted: Fred,56,78,99 with each user on a new line.

任何帮助将不胜感激.

import csv
import operator

sample  = open("sampleData.txt", "r")

csv1 = csv.reader(sample, delimiter = ',')

sort = sorted(csv1,key=operator.itemgetter(0))

for i in range( 0, len(sort)):
    sort[i].append((int(sort[i][1]) + int(sort[i][2]) + int(sort[i][3])) / int(len(sort[i])-1))   
sort = list(reversed(sorted(sort,key=operator.itemgetter(4))))
for i in range( 0, len( sort ) ):
print(sort[i][0], round(sort[i][4]))

推荐答案

import csv

sample  = open("sampleData.txt", "r")
csv1 = csv.reader(sample, delimiter = ',')

sorted_list = []

for line in csv1:
    print '-- ORIG:', line
    tmp = sorted( [int(i) for i in line[1:]], reverse=True )  # eg: [99,78,56]
    stat_list = [round(sum(tmp)/float(len(tmp)), 2), min(tmp), max(tmp)]
    sorted_list.append( [line[0]] + tmp + stat_list )

for s in sorted_list: print '** NEW: ', s # has ['Fred',99,78,56,78.0,57,99]

您可以使用/修改快速&上面的脏解决方案.注意:

You can use/modify the quick & dirty solution above. Note:

  1. 结果是将数字转换为整数的列表的列表.
  2. 需要float()来计算平均值-仅对分母进行计算就足以使整个结果成为浮点数.
  3. 列表推导是便捷的快捷方式,可有效避免for循环.
  4. numpy 模块具有内置的mean()函数(以及其他许多函数),该函数非常有用且快速,特别是对于大型数组.
  1. The result is a list of lists with digits converted to integers.
  2. The float() is needed for computing average - just doing it on the denominator is enough for the whole result to be a float.
  3. List comprehensions are great shortcuts and efficient for avoiding for loops.
  4. The numpy module has builtin mean() function (among many others) that are useful and fast, especially for large arrays.

输出(添加空格)

  • 原件:['Fred','57','78','99']
  • 原件:['Wilma','96','4','105']
  • 原点:['Bar','23','88','65']

    OUTPUT (space added)

    • ORIG: ['Fred', '57', '78', '99']
    • ORIG: ['Wilma', '96', '4', '105']
    • ORIG: ['Bar', '23', '88', '65']

      新功能:['Fred',99,78,57,78.0,57,99]

      NEW: ['Fred', 99, 78, 57, 78.0, 57, 99]

      这篇关于查找从CSV文件Python生成的列表的最小值和最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆