如何访问包含 500000 个元素的列表,并且列表中的每个元素应小于 1500000 (Python)?

问题描述 投票:-2回答:1

列表中包含 500000 元素,即。size of list.

而列表中的每个元素都应该小于 1500000.

l1 = [1]*500000
for i in range(len(l1)):
    if l1[i] <= 1500000:
        print("valid)

上面的方法会花费更多的时间来循环(may error out if size is greater than 500000)我知道这不是正确的方法。可能是 itertools 或更好的东西将是理想的。

Could you please help me to handle in efficient way ?

如果用户输入了这样的值,如何读取它们?specific/faster 接受这些值的方法?input()

python-3.x list time-complexity itertools
1个回答
1
投票

你需要使用 numpy 为了更快,用list和任何工具都不能比numpy数组更快。

import numpy as np
# generating random list(numpy array of 500000 elements with random between 0 and 10000 )
l1 = np.random.randint(0,10000, (500000,))
#print all elements whose greter than 1500
print(l1[l1 > 1500])

numpy运营商请访问 这个这个

© www.soinside.com 2019 - 2024. All rights reserved.