Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从列表中减去索引?_Python_List_Indexing_Indices_Operation - Fatal编程技术网

Python 如何从列表中减去索引?

Python 如何从列表中减去索引?,python,list,indexing,indices,operation,Python,List,Indexing,Indices,Operation,我有一个非常大的列表,大约有300万个元素,比如说 x = [1, 2, 3, 4, 5, 6, ..., 3000000] 我试着从中减去一个数字,比如8,(输入方式与此完全相同:x-8),谢天谢地,它给了我另一个相同数量元素的列表,但是从中减去了8 像 [7,-6,-5,-4,-3,-2,…,299992] 但我还有另外一张单子,比如说 otherlist = [1, 2, 3, 4, 5, 6, 7, 8] 其中otherlist[7]=8当我尝试执行相同的减法(x-otherlist

我有一个非常大的列表,大约有300万个元素,比如说

x = [1, 2, 3, 4, 5, 6, ..., 3000000]
我试着从中减去一个数字,比如8,(输入方式与此完全相同:x-8),谢天谢地,它给了我另一个相同数量元素的列表,但是从中减去了8 像

[7,-6,-5,-4,-3,-2,…,299992]

但我还有另外一张单子,比如说

otherlist = [1, 2, 3, 4, 5, 6, 7, 8]
其中
otherlist[7]=8
当我尝试执行相同的减法(
x-otherlist[7]
)时,它让我抓狂&不能像以前一样给我相同的输出

我如何处理这个问题?我已经尝试过创建一个单独的列表,列出

separatelist=[0,1,2,…,299999]

比如说 所以我可以用它作为索引来迭代我原来的x列表

x[m] - otherlist[7] for m in separatelist

但这与不处理的问题相同。

您可以使用numpy来减去元素。使用numpy会更快

In [107]: import numpy as np
In [108]: lst = np.array(range(3000000))

In [109]: otherlist = np.array([1, 2, 3, 4, 5, 6, 7, 8])

In [110]: lst - otherlist[-1]
Out[110]: array([     -8,      -7,      -6, ..., 2999989, 2999990, 2999991])

只使用列表会很慢

In [115]: otherlist = [1, 2, 3, 4, 5, 6, 7, 8]

In [116]: lst = list(range(3000000))

In [117]: [x - otherlist[-1] for x in lst]

如果你想从列表中删除数字8,那么你可以使用删除功能

x.remove(8)
或者,如果你想用8减去所有数字,那么:

x = [1, 2, 3, 4, 3000000]

y = []

for num in x:
    subtracted = num - 8
    y.append(subtracted)

print(y)
 

你在用numpy吗?通常,从列表中减去一个数字是不受支持的操作。如果列表是一个numpy数组,它可能会工作
x-8
对于此处显示的
x
不是有效的操作。请注意,遍历列表时不需要索引列表–您可以对列表中的元素执行
,或者,如果需要索引(例如修改),则对枚举(列表)中的元素执行