Если имеется только два вложенных элемента list
и требуются разные условия filter
, примените к нему индивидуально и назначьте выход обратно элементу list
. Проходим по мастеру list
с помощью map
, а затем применяем логические условия
library(purrr)
library(dplyr)
lst2 <- map(lst1, ~ {
.x[[1]] <- .x[[1]] %>%
filter_at(4, all_vars(. > 6))
.x[[2]] <- .x[[2]] %>%
filter_at(5, all_vars(. == 'y'))
.x
})
. Я recommned, использующий поточную обработку модуля. Еще больше преимущества состоит в том, чтобы использовать InterruptableThread для завершения потока. Вы не должны использовать флаг для завершения Вашего потока, но исключение произойдет, если Вы назовете оконечными () на этом потоке от родителя. Можно обработать исключение или нет.
import threading, ctypes
class InterruptableThread(threading.Thread):
@classmethod
def _async_raise(cls, tid, excobj):
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(excobj))
if res == 0:
raise ValueError("nonexistent thread id")
elif res > 1:
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
raise SystemError("PyThreadState_SetAsyncExc failed")
def raise_exc(self, excobj):
assert self.isAlive(), "thread must be started"
for tid, tobj in threading._active.items():
if tobj is self:
self._async_raise(tid, excobj)
return
def terminate(self):
self.raise_exc(SystemExit)
Править: Можно переписать код как это использование другого потока, который ожидает 1 минута и затем уничтожает другой поток
def send_data:
IP = ...
# other vars
...
s = socket.socket(.....)
# no killed checking
# no time checking
# just do your work here
...
s.close()
my_thread = InterruptableThread(target=send_data)
my_thread.start()
def one_minute_kill(who):
time.sleep(60)
who.terminate()
killer_thread = InterruptableThread(target=one_minute_kill, args=[my_thread])
killer.start()
print "to quit type quit"
while my_thread.isAlive():
if raw_input("Enter something: ") == "quit":
my_thread.terminate()
Я не знаю, как сделать это с модулем "потока", но я могу сделать это с модулем "поточной обработки". Я думаю, что этот код выполняет то, что Вы хотите.
Для документации относительно модуля поточной обработки: http://docs.python.org/library/threading.html
#!/usr/bin/python
import time
from threading import Thread
import threading
import sys
test_time = 10
killed = False
class SillyThread( threading.Thread ):
def run(self):
global killed
starttime = time.time()
counter = 0
while (time.time() - starttime) < test_time:
if killed:
break
counter = counter + 1
time.sleep(0.1)
print "I did %d loops" % counter
class ManageThread( threading.Thread ):
def run(self):
global killed
while True:
var = raw_input("Enter something: ")
if var == "quit":
killed = True
break
print "Got var [%s]" % var
silly = SillyThread()
silly.start()
ManageThread().start()
Thread.join(silly)
print "bye bye"
sys.exit(0)
Обратите внимание, что я использую time.time () вместо time.clock (). time.clock () дает истекшее процессорное время на Unix (см. http://docs.python.org/library/time.html). Я думаю, что time.clock () должен работать везде. Я установил свой test_time на 10 секунд, потому что у меня нет терпения в течение минуты.
Вот то, что происходит, если я позволяю ему выполнить целые 10 секунд:
leif@peacock:~/tmp$ ./test.py
Enter something: I did 100 loops
bye bye
Вот то, что происходит, если я ввожу 'выход':
leif@peacock:~/tmp$ ./test.py
Enter something: quit
Got var [quit]
I did 10 loops
bye bye
Надеюсь, это поможет.
Как упомянуто выше, используйте модуль поточной обработки, это намного легче использовать и обеспечивает несколько примитивов синхронизации. Это также обеспечивает класс Таймера, который бежит за указанным количеством времени.
Если Вы просто хотите, чтобы программа вышла, можно просто сделать передающий поток демоном. Вы делаете это путем вызова setDaemon (Верный), прежде чем вызов запустится () (2.6, мог бы использовать атрибут демона вместо этого). Python не выйдет, пока поток недемона работает.
Удостоверьтесь, что "выход" работает правильно, и добавьте мелкий шрифт для тестирования этого, вход работает.
if var == "quit":
print "Hey we got quit"
Легко протестировать объем killed
:
>>> import thread
>>> killed = False
>>> import time
>>> def test():
... while True:
... time.sleep(1)
... if killed:
... print 'Dead.'
... break
...
>>> thread.start_new_thread(test, ())
25479680
>>> time.sleep(3)
>>> killed = True
>>> Dead.
Истекшая переменная не инициализируется. Обнулите его выше цикла с условием продолжения.
You can do this pretty easily without threads. For example, using Twisted, you just set up a timed call and a producer:
from twisted.internet.protocol import ClientFactory, Protocol
from twisted.internet import reactor
class Noisy(Protocol):
def __init__(self, delay, data):
self.delay = delay
self.data = data
def stop(self):
self.transport.unregisterProducer()
self.transport.loseConnection()
reactor.stop()
def resumeProducing(self):
self.transport.write(self.data)
def connectionMade(self):
self.transport.registerProducer(self, False)
reactor.callLater(self.delay, self.stop)
factory = ClientFactory()
factory.protocol = lambda: Noisy(60, "hello server")
reactor.connectTCP(host, port, factory)
reactor.run()
This has various advantages over the threaded approach. It doesn't rely on daemon threads, so you can actually clean up the network connection (eg, to send a close message if necessary) rather than relying on the platform to destroy it. It handles all the actual low level networking code for you (your original example is doing the wrong thing in the case of socket.send returning 0; this code will handle that case properly). You also don't have to rely on ctypes or the obscure CPython API for raising an exception in another thread (so it's portable to more versions of Python and can actually interrupt a blocked send immediately, unlike some of the other suggested approaches).