python中的数字操作

2024-04-25 21:35:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我不熟悉脚本语言。我有一个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文件,但我不确定如何继续

^{pr2}$

我期待着继续印刷

最大正差:11

最大负差:29


Tags: 文件脚本定义数字xls事情excel脚本语言
3条回答

给你:

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])

输出:

^{pr2}$

更新:短版

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))])

我想这就是你想要的

(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

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

#! /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] )

相关问题 更多 >