社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

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

Joseph • 5 年前 • 1540 次点击  

假设我有以下两个列表:

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 in x[5:]:
  result.append(x[i] - y[i])

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

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/53057
 
1540 次点击  
文章 [ 6 ]  |  最新文章 5 年前
Mykola Zotko
Reply   •   1 楼
Mykola Zotko    6 年前

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]
Kaustabh
Reply   •   2 楼
Kaustabh    6 年前

试试这个,它会处理两个列表中的“无”。我们不需要手动跟踪它们。如果不需要前5个,我们可以在减法运算上加一个切片。

subtrct=[None if val is None else (val - (0 if y[index] is None else y[index])) for index, val in enumerate(x)]
Nenri
Reply   •   3 楼
Nenri    6 年前

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

另外,由于您的两个列表大小相同,您可以压缩它们,以使代码看起来更好,因此这里有一个压缩列表的解决方案:

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])
Rakesh
Reply   •   4 楼
Rakesh    6 年前

你可以用 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]
Mike Scotty
Reply   •   5 楼
Mike Scotty    6 年前

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) ]
ruohola
Reply   •   6 楼
ruohola    6 年前

你应该这样做:

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 在你的循环中被赋值(不是索引!)的 x i = 15 当该元素的索引仅为 14 .