0

没有很多python /编程经验。我需要测试 1 到 10 亿之间的每个数字,然后将某些数字附加到列表中。目前我正在尝试使用 range( 0 , Billion ) ,但我发现在我的机器上使用 Python 3.3 大约需要 80 秒。有没有更有效的方法来做到这一点?

for i in range(0, Billion)
    # if i passes test
    i.append(samplelist)
4

3 回答 3

3

不。考虑一下机器时间方面的代码。您的测试和附加功能无法触及,因此我们剩下的只是 for i in range。这是你的基本 for 循环,它是你能得到的最基本的。您可以编写一个while循环并编写另一行来增加 i 自己,但我怀疑这实际上会增加您的执行时间,因为您正在对必须处理的python解释器进行更多调用。

再想一想,如果你能优化你的测试程序......

于 2013-03-06T03:13:19.783 回答
2

Usually, if you need to iterate up to 1000000000, there's some better way. For example, you can use some mathematical property to avoid testing every number:

samplelist = [x**2 for x in range(int(1000000000**0.5))] # get all perfect squares up to 1000000000

Python's not really that fast for numerical operations. So, iterating to 1000000000 and doing something at every single iteration is going to be slow; there's no way around this except to try a faster interpreter (e.g. PyPy), or write the code in a more performant language like C.


Alternatively, if you are adding a huge number of elements to a list, then consider using a generator instead. This will avoid the overhead of creating a massive list, while still being useful for many things:

def gen_numbers(n):
    for i in range(n):
        if <i passes test>:
            yield i

for i in gen_numbers(1000000000):
    print(i)
于 2013-03-06T03:11:34.857 回答
0

This should be a little faster, but most of the time is probably spent calling some_test()

samplelist = [i for i in range(1000000000) if some_test(i)]
于 2013-03-06T03:11:28.073 回答