如何从排序列表中选择小于给定整数的元素? [英] How can I select elements lesser than a given integer, from a sorted list?

查看:53
本文介绍了如何从排序列表中选择小于给定整数的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有素数数组,例如在0到1000之间的整数

I have array of primes e.g. between integers 0 to 1000

primes = [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]

我得到输入

n = int(input())

将数组切片为新数组(数组的最后一个元素小于n的最有效方法)是什么?

What is the most efficient way to slice array to new array where last element of array will be less than n?

推荐答案

您可以利用

You can make use of the fact that primes is already sorted, with bisect, like this

>>> from bisect import bisect
>>> primes[:bisect(primes, n)]

bisect对输入列表进行二进制搜索,并返回小于n的元素的索引.

bisect does binary search on the input list and returns the index of the element which is lesser than n.

这篇关于如何从排序列表中选择小于给定整数的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆