2

我是脚本语言的新手。我有一个具有以下编号的 excel (xls,2003) 文件

2      48
3      49
6      57
11     89
19     120
29     110
32     105

我正在尝试执行以下操作

  1. 阅读excel文件:我做了
  2. 在正负意义上找到第 2 列中两个连续数字之间的差异。
  3. 在第 2 列定义的第 2 列中,当差异在正或负意义上最大时,在第 1 列中找到相应的数字。

我为读取 excel 文件完成了以下脚本,但我不确定如何继续

import xlrd

myexcel = xlrd.open_workbook('sample.xls')
#print "WorkSheets:", myexcel.sheet_by_names()
sheet = myexcel.sheet_by_index(0)

c = sheet.col_values(1)
print c

#data = [] #make a data store

我期待跟随打印

最大正差:11

最大负差:29

4

3 回答 3

1

干得好:

col1 = [2, 3, 6, 11, 19, 29, 32]
col2 = [48, 49, 57, 89, 120, 110, 105]

pd, nd, pi, ni = 0, 0, -1, -1
for i in range(len(col2)-1):
    d = col2[i+1] - col2[i]
    if d > 0 and d > pd:
        pd, pi = d, i
    if d < 0 and abs(d) > nd:
        nd, ni = abs(d), i

print "Max positive difference :" + str(col1[pi+1])
print "Max negative difference :" + str(col1[ni+1])

输出:

>>> 
Max positive difference :11
Max negative difference :29

更新:短版

col1 = [2, 3, 6, 11, 19, 29, 32]
col2 = [48, 49, 57, 89, 120, 110, 105]

m = [(x[1] - x[0]) for x in zip(col2[:1] + col2, col2 + col2[-1:])]

print "Max positive difference :" + str(col1[m.index(max(m))])
print "Max negative difference :" + str(col1[m.index(min(m))])
于 2013-03-03T19:58:00.803 回答
0

我认为这就像你要找的东西

(max_pos_difference, max_pos_row_col_1_value, neg_row_col_1_value, max_neg_row_col_1_value) = get_max_row()

print "Pos val: {} Pos row: {} Neg val: {} Neg row: {}".format(max_pos_difference, max_pos_row_col_1_value, neg_row_col_1_value, max_neg_row_col_1_value)

def get_max_row():
    max_pos_difference = 0
    max_neg_difference = 0
    max_pos_row = 0
    max_neg_row = 0
    for rownum in range(sheet.nrows):
        if rownum <= sheet.nrows - 1:
            this_row_value = sheet.cell(rownum, 1).value
            next_row_value = sheet.cell(rownum+1, 1).value
            difference = next_row_value - this_row_value

        if difference > max_pos_difference and difference >= 0:
            max_pos_difference = difference
            max_pos_row = rownum

        if difference < max_neg_difference and difference < 0:
            max_neg_difference = difference
            max_neg_row = rownum

    return (max_pos_difference, sheet.cell(max_pos_row, 0).value, max_neg_difference, sheet.cell(max_neg_row, 0).value
于 2013-03-03T20:08:48.613 回答
0

您可以在不过度使用局部变量、循环和条件的情况下尝试此操作:

#! /usr/bin/python

col1 = [2, 3, 6, 11, 19, 29, 32]
col2 = [48, 49, 57, 89, 120, 110, 105]

difs = [ (a, c - b) for a, b, c in zip (col1 [1:], col2, col2 [1:] ) ]
print (max (difs, key = lambda x: x [1] ) [0] )
print (max (difs, key = lambda x: -x [1] ) [0] )
于 2013-03-03T20:28:24.670 回答