我有一份清单如下:
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
但是,我更喜欢一个更加动态的版本,它可以根据每个子列表中的元素数量进行扩展。在数学上,n个元素将有n - 1个第一个微分x。
答案 0 :(得分:1)
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
这是我的工作代码。我希望这就是你的意思。
----&GT; v这是固定的v&lt; ----
我只有一个问题 - 例如:
difference = 0.001
tmp = [0.000999999999999994]
差异(z变量)附加到tmp,而tmp看起来像“舍入”而不是完整的0.001,我真的不知道如何正确格式化它:(。
我现在会尝试使用它,如果我设法以某种方式进行操作,我将编辑我的帖子。
@@@@ FIX EDIT:@@@@@
我通过将差值更改为str而不是将其保留为float来修复它。