Skip to main content
 首页 » 编程设计

python之python中的数字操作

2025年05月04日8tuyile006

我刚接触脚本语言。我有一个具有以下编号的 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

请您参考如下方法:

给你:

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