为什么即使我不对数组进行排序?

时间:2019-02-06 18:27:22

标签: python

问题在于,将值附加到第二个数组(arr1)之后,它们会以某种方式排序,而我不希望这样做。

我也搜索了google,但是我找不到原因

代码:

from math import sqrt
def primes(limit):
    tab = []
    for i in range(2, limit):
        for j in tab:
            if i % j == 0: break
        else:
            yield i
            tab.append(i)

def isPrime(n):
    return n > 1 and all(n % d != 0 for d in range(2, int(sqrt(n))))

arr = []
arr1 = []
arr2 = []
arr3 = list(range(0,1000))
count = 0
count1 = 0
with open("inp.txt") as f:
    for line in f:
        arr.append(int(line.rstrip()))
    f.close()
for i in primes(63):
    if isPrime(i):
        for val in arr:
            if val == pow(2,i) - 1:
                arr1.append(val)
for val in arr1:
    print(val)

还有inp.txt:

3
3
3
7
3
3
3

我想看:

3
3
3
7
3
3
3

但是我得到了

3
3
3
3
3
3
7

1 个答案:

答案 0 :(得分:0)

这看起来像是一项家庭作业,因此,我将尽最大努力不给出答案,只为您提供帮助。我将在此for循环的上方放入打印语句,以确保arr符合您想要的顺序。也许这会为您指明正确的方向。

  // print arr and check that it is in the correct order //
 for val in arr:
     // if arr is in the correct order check math being pow //
     if val == pow(2,i) - 1:
         arr1.append(val)
 for val in arr1:
     print(val)