首页 > 解决方案 > 从python中的列表中减去每个索引处的值

问题描述

嗨,我想从 x 获取每个索引处的 x 值,以计算 y,最好对所有索引使用 for 循环

x = [1,2,3,4,5,6,7,8,9,10]
indexes_for_x =[0,1,2,3]

#subtract values of x at each index from x to calculate y
# for index 0 since x = 1 result should look like below
y_at_index_0 = [0,1,2,3,4,5,6,7,8,9]

标签: pythonlistindexing

解决方案


我希望我已经正确理解了你的问题。如果你想从中减去每个值,x[<indexes_for_x>]你可以这样做:

x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
indexes_for_x = [0, 1, 2, 3]

for v in indexes_for_x:
    print(f"y_at_index_{v} = {[w - x[v] for w in x]}")

印刷:

y_at_index_0 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
y_at_index_1 = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8]
y_at_index_2 = [-2, -1, 0, 1, 2, 3, 4, 5, 6, 7]
y_at_index_3 = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6]

推荐阅读