我有一个列表如下:
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。