Skip to main content
 首页 » 编程设计

Python:如何将列表切片为特定值

2025年05月04日8wayfarer

我想知道是否有办法将现有列表分割成某个很可能不在列表中的数字。例如,假设我有:

primes = [2,3,5,7] 

现在我想测试数字 11 是否正直。我将通过在 1 + 整数平方根 11 的限制下尝试除以所有素数来做到这一点。因此,与其遍历列表中的所有元素,素数并在元素大于限制时中断循环,我想知道我是否可以将列表拼接到 Limit 的值。在这种情况下,该值将是:

1 + int(sqrt(11)) = 1 + 3 = 4 

所以我可以遍历 primes[ : up until the value of 4] or [2,3]

我知道一些 python,但我不确定如何仅使用列表方法来做到这一点……对于多达数十亿的筛选方法,我可以通过不使用 if 语句来有效地节省时间……

再次提前致谢!

请您参考如下方法:

我不太确定我完全理解了这个问题(很抱歉,如果我没有理解,如果它没有帮助我会删除答案)但也许是 bisect模块(它只适用于排序列表,但如果有效,它会非常快)在这种情况下会有一些帮助:

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 
 
import bisect 
import math 
 
primes = [2,3,5,7]  
searchedPrime=11 
lookedPosition = 1 + int(math.sqrt(searchedPrime))  
 
checkUntil = primes[:bisect.bisect_left(primes, lookedPosition)] 
print "I just have to check %s positions: %s" % (len(checkUntil), checkUntil) 

这输出

I just have to check 2 positions: [2, 3] 

所以可能是 sqrt 方法和 bisect 的组合工具将帮助您确定要检查的素数范围。

编辑:

哦,看看那个……我不知道 sqrt这东西很适合寻找素数……但它看起来像是……

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 
import bisect 
import math 
 
foundPrimes = []  
def isPrime(number, otherPrimes): 
  global foundPrimes 
  lookedPosition = 1 + int(math.sqrt(number))  
  formerPrimes = foundPrimes[:bisect.bisect_left(foundPrimes, lookedPosition)] 
  for prime in formerPrimes: 
    if prime > 1 and number % prime == 0: 
      return False 
  return True 
 
def getPrimes(upperLimit): 
  for i in range(1, upperLimit): 
      if isPrime(i, foundPrimes): 
        foundPrimes.append(i) 
  return foundPrimes 
 
print "Primes: %s" % getPrimes(1000) 

这个输出:

Primes: [1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997] 

...在我看来很原始...:-)

P.S.:不要像那样使用该代码...这是废话。