如何在Python中的两个长列表中减去特定切片的相应元素?

时间:2019-02-25 10:24:00

标签: python

假设我有以下两个列表:

x = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]

y = [None,None,None,None,None,10,20,30,40,50,60,70,80,90,100]

我需要减去每个列表的对应元素(x [i]-y [i]),我想开始从x的第六个元素减去6,以便y中的对应元素不为null(没有)。 以下代码是我尝试并得到的错误:

result = []

for i in x[5:]:
  result.append(x[i] - y[i])

索引错误:列表索引超出范围

6 个答案:

答案 0 :(得分:3)

您应该这样做:

find /opt/lampp/htdocs -type f -exec chmod 644 {} \;

OR

for val1, val2 in zip(x[5:], y[5:]):
    result.append(val1 - val2)

您还可以跳过for val1, val2 in list(zip(x, y))[5:]: result.append(val1 - val2) 值,如下所示:

None

获取for val1, val2 in zip(x, y): if val2 is not None: # can also check if val1 is not None if needed result.append(val1 - val2) 的原因是,循环中的IndexError被分配了i列表中的值(而不是indeses!),您正在尝试用这些值索引列表。因此,例如在循环x的最后一步,该元素的索引仅为i = 15

答案 1 :(得分:1)

由于尝试访问y[15](因为15是x[14]的值),您会收到一条错误消息。

但是y只有15个元素,并且由于列表项从索引0开始,因此您得到list index out of range

一种更灵活的方法-只要两个列表的长度相同,就使用zip并跳过None值:

x = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]

y = [None,None,None,None,None,10,20,30,40,50,60,70,80,90,100]

result = []

for val_x, val_y in zip(x, y):
    if(val_y is None):
        continue
    result.append(val_x - val_y)

print(result)

输出:

[-4, -13, -22, -31, -40, -49, -58, -67, -76, -85]

或作为列表理解:

result = [ (val_x - val_y) for val_x, val_y in zip(x, y) if (val_y is not None) ]

答案 2 :(得分:0)

您可以使用enumerate

例如:

x = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
y = [None,None,None,None,None,10,20,30,40,50,60,70,80,90,100]

result = []
for i, v in enumerate(x[5:], 5):
    result.append(v - y[i])
print(result)

输出:

[-4, -13, -22, -31, -40, -49, -58, -67, -76, -85]

答案 3 :(得分:0)

正如@meowgoesthedog在评论中所说,数组索引从0开始。

另外,由于您的2个列表大小相同,您可以将它们压缩以使代码看起来更好,所以这是带有压缩列表的解决方案:

result = []

for i, j in list(zip(x, y))[5:]:
  result.append(i - j)

这是一个没有:

的解决方案
result = []

for i in range(x[5:] - 1):
  result.append(x[i] - x[j])

答案 4 :(得分:0)

尝试此操作,它将同时处理两个列表中的“无”。我们不需要手动跟踪它们。如果我们不需要前5个,则可以在减法上添加一个切片。

subtrct=[None if val is None else (val - (0 if y[index] is None else y[index])) for index, val in enumerate(x)]

答案 5 :(得分:0)

您可以使用功能starmap()dropwhile()

from itertools import starmap, dropwhile

x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
y = [None, None, None, None, None, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

# substract corresponding elements
m = starmap(lambda x, y: x - y if y else None, zip(x, y))

# filter None
list(dropwhile(lambda x: not x, m))
# [-4, -13, -22, -31, -40, -49, -58, -67, -76, -85]