我有一个包含整数值的Python列表。例如,以下列表:
p = [10,44,55,33]
现在,我想测试列表中的至少一个值是否落入给定间隔。例如,如果我们有间隔[15,30]
,则它是错误的,因为在此间隔中,p中没有值。如果我们有间隔[50,60]
,则为真,因为55在此间隔中。
我不仅像上面的示例那样在列表中有4个值,而且还有数十个tousand,所以我搜索了最有效的方法。最好的方法是什么?
答案 0 :(得分:4)
答案 1 :(得分:0)
除非对p进行排序,否则最好的办法是扫描p的每个元素并检查它是否在间隔中。
您可以这样做:
any( interval_low <= i <= interval_high for i in p )
答案 2 :(得分:0)
p = [10,44,55,33]
i = [10,50]
sol = list(filter(lambda x: x in range(i[0],i[1]+1),p))
# output [10, 44, 33]
答案 3 :(得分:0)
使用列表理解
from twisted.internet import threads, reactor
from twisted.internet.defer import inlineCallbacks, returnValue
from time import sleep
class SomeClass(object):
def __init__(self):
self.working = False
def set_working(self, is_working):
self.working = is_working
print 'Flag set to {}'.format(is_working)
@inlineCallbacks
def do_worker_thread(self):
# I want to make this call on the main thread
self.set_working(True)
# I want to do all this garbage on a separate thread and keep trucking on the main thread
# This mimics some calls in the real code. There is a call to deferToThread and a try
# except block there.
def thread_proc():
try:
for i in xrange(0, 10):
print 'Step {} starting'.format(i)
self.execute_step(i)
except Exception:
print 'An exception happened'
yield threads.deferToThread(thread_proc)
# When the worker thread is done, I want to call back 'on_thread_work_done'
self.on_thread_work_done()
returnValue(17)
def execute_step(self, num):
sleep(1)
print 'Worker thread: {}'.format(num)
def on_thread_work_done(self):
"""I want to be called back when the worker thread is done"""
self.set_working(False)
def do_main_thread(self):
for i in [chr(x) for x in range(ord('a'), ord('z')+1)]:
print 'Main thread: {}'.format(i)
sleep(1)
def thread_done(self, result):
print 'Thread done: {}'.format(result)
if __name__ == "__main__":
someClass = SomeClass()
# Schedule the threaded work
result = someClass.do_worker_thread().addCallback(someClass.thread_done)
# Schedule the main thread work
reactor.callFromThread(someClass.do_main_thread)
reactor.run()