Math 如何找到列表中元素之间的第一个差异?

Math 如何找到列表中元素之间的第一个差异?,math,for-loop,python-2.7,Math,For Loop,Python 2.7,我的清单如下: data = [ [0.051, 0.05], [], [], [], [], [], [0.03], [0.048], [], [0.037, 0.036, 0.034, 0.032], [0.033, 0.032, 0.03] ] 我试图找出每个子列表中元素之间的第一个区别,但不太清楚如何使用python实现这一点。以下是我写的: x = {} index = 0 for item in data: if len(item) < 2: x[in

我的清单如下:

data = [
[0.051, 0.05],
[],
[],
[],
[],
[],
[0.03],
[0.048],
[],
[0.037, 0.036, 0.034, 0.032],
[0.033, 0.032, 0.03]
]
我试图找出每个子列表中元素之间的第一个区别,但不太清楚如何使用python实现这一点。以下是我写的:

x = {}
index = 0
for item in data:
    if len(item) < 2:
        x[index] = "NA"      
        index += 1
    else:
        try:
            x[index] = item[0] - item[1]
            index += 1        
        except IndexError:
            x[index] = "NA"
            index += 1
y = {}
index = 0
for item in data:
    if len(item) < 2:
        y[index] = "NA"      
        index += 1
    else:
        try:
            y[index] = item[1] - item[2]
            index += 1        
        except IndexError:
            y[index] = "NA"
            index += 1
z = {}
index = 0
for item in data:
    if len(item) < 2:
        z[index] = "NA"      
        index += 1
    else:
        try:
            z[index] = item[2] - item[3]
            index += 1        
        except IndexError:
            z[index] = "NA"
            index += 1
x={}
索引=0
对于数据中的项目:
如果长度(项目)<2:
x[索引]=“NA”
指数+=1
其他:
尝试:
x[索引]=项目[0]-项目[1]
指数+=1
除索引器外:
x[索引]=“NA”
指数+=1
y={}
索引=0
对于数据中的项目:
如果长度(项目)<2:
y[索引]=“NA”
指数+=1
其他:
尝试:
y[索引]=项目[1]-项目[2]
指数+=1
除索引器外:
y[索引]=“NA”
指数+=1
z={}
索引=0
对于数据中的项目:
如果长度(项目)<2:
z[索引]=“NA”
指数+=1
其他:
尝试:
z[索引]=项目[2]-项目[3]
指数+=1
除索引器外:
z[索引]=“NA”
指数+=1
但是,我更喜欢一个更动态的版本,它可以根据每个子列表中的元素数量进行扩展。从数学上讲,n个元素将有n-1个第一微分x

data = [
[0.051, 0.05],
[],
[],
[],
[],
[],
[0.03],
[0.048],
[],
[0.037, 0.036, 0.034, 0.032],
[0.033, 0.032, 0.03]
]

x = {}
for i in range(0,len(data)):
    tmp = []
    #print "\ndata[i]= ", data[i]
    try:
        z = 0
        for s in range(0,len(data[i])):
            try:
                z = str(data[i][s] - data[i][s+1])   #WITHOUT THIS STR() HERE VALUES GOT ROUNDED - so instead of getting 0.001 it was 0.000999999999994 or sth like that.
                #print "difference = ", z
                tmp.append(z)
                #print "tmp = ", tmp
            except:
                pass
                #print "inside error"
    except:
        pass
        #print "error"#, i
    x[i+1] = tmp

print x
这是我的工作代码。我希望这就是你的意思


---->这是固定的,这真是太棒了。我的代码太长,没有经过优化。
difference = 0.001
tmp = [0.000999999999999994]