相关疑难解决方法(0)

有没有一种简单的方法可以按值删除列表元素?

a = [1, 2, 3, 4]
b = a.index(6)

del a[b]
print a
Run Code Online (Sandbox Code Playgroud)

以上显示以下错误:

Traceback (most recent call last):
  File "D:\zjm_code\a.py", line 6, in <module>
    b = a.index(6)
ValueError: list.index(x): x not in list
Run Code Online (Sandbox Code Playgroud)

所以我必须这样做:

a = [1, 2, 3, 4]

try:
    b = a.index(6)
    del a[b]
except:
    pass

print a
Run Code Online (Sandbox Code Playgroud)

但有没有更简单的方法来做到这一点?

python list

888
推荐指数
14
解决办法
162万
查看次数

python defaultdict:0 vs. int和[] vs list

传递intlambda: 0作为参数之间有什么区别吗?或者之间listlambda: []

看起来他们做同样的事情:

from collections import defaultdict
dint1 = defaultdict(lambda: 0)
dint2 = defaultdict(int)
dlist1 = defaultdict(lambda: [])
dlist2 = defaultdict(list)

for ch in 'abracadabra':
    dint1[ch] += 1
    dint2[ch] += 1
    dlist1[ch].append(1)
    dlist2[ch].append(1)

print dint1.items()
print dint2.items()
print dlist1.items()
print dlist2.items()
## -- Output: --
[('a', 5), ('r', 2), ('b', 2), ('c', 1), ('d', 1)]
[('a', 5), ('r', 2), ('b', 2), ('c', 1), ('d', 1)]
[('a', [1, 1, 1, 1, 1]), …
Run Code Online (Sandbox Code Playgroud)

python collections defaultdict

35
推荐指数
1
解决办法
3万
查看次数

过滤器是否是线程安全的

我有一个更新名为的列表的线程l.我是否正确地说从另一个线程执行以下操作是线程安全的?

filter(lambda x: x[0] == "in", l)
Run Code Online (Sandbox Code Playgroud)

如果它不是线程安全的,那么这是正确的方法:

import threading
import time
import Queue

class Logger(threading.Thread):
    def __init__(self, log):
        super(Logger, self).__init__()
        self.log = log
        self.data = []
        self.finished = False
        self.data_lock = threading.Lock()

    def run(self):
        while not self.finished:
            try:
                with self.data_lock: 
                    self.data.append(self.log.get(block=True, timeout=0.1))
            except Queue.Empty:
                pass

    def get_data(self, cond):
        with self.data_lock: 
            d = filter(cond, self.data)      
        return d 

    def stop(self):
        self.finished = True
        self.join()  
        print("Logger stopped")
Run Code Online (Sandbox Code Playgroud)

其中该get_data(self, cond)方法用于以线程安全的方式检索self.data中的一小部分数据.

python

18
推荐指数
1
解决办法
550
查看次数

python的"in"语言是否构成了列表的线程安全?

是否可以在不同的线程中修改obj in a_list线程安全a_list

这是一个全面但非详尽list操作示例列表,以及它们是否是线程安全的,但我找不到任何in语言结构的参考.

在python实现方面,我使用CPython,但其他实现的答案对社区也有帮助.

python list thread-safety in-operator

8
推荐指数
1
解决办法
994
查看次数

定义Python类

我正在尝试自己学习Python,因此,我得到了一个用C#编写的软件,并试图用Python重新编写它.鉴于以下课程,我有几个问题:

C#

sealed class Message
{
    private int messageID;
    private string message;
    private ConcurrentBag <Employee> messageFor;
    private Person messageFrom;
    private string calltype;
    private string time;


    public Message(int iden,string message, Person messageFrom, string calltype,string time)
    {
        this.MessageIdentification = iden;
        this.messageFor = new ConcurrentBag<Employee>();
        this.Note = message;
        this.MessageFrom = messageFrom;
        this.CallType = calltype;
        this.MessageTime = time;
    }

    public ICollection<Employee> ReturnMessageFor
    {
        get
        {
            return messageFor.ToArray();
        }

    }
Run Code Online (Sandbox Code Playgroud)
  1. 在我的类中,我有一个名为messageFor的线程安全集合,在Python中是否存在等价物?如果是这样,我如何在python类中实现它?

  2. 我的线程安全集合也有一个吸气剂?我如何在Python中做同样的事情?

  3. Python有一个EqualsTo方法来测试对象之间的相等性吗?或者相当于Python中的这个?

        public override bool Equals(object obj)
        {
            if (obj == null)
            {
                return …
    Run Code Online (Sandbox Code Playgroud)

c# python

5
推荐指数
1
解决办法
247
查看次数

is list.pop thread safe in python

lets say I have a program which initializes a list with random values. The application then spawns a bunch of threads and each thread keeps popping items out of this shared list. My question is , is this operation thread safe :

try:
    while global_list.pop():
        ...do something ..
except:
    print ("list is empty")
Run Code Online (Sandbox Code Playgroud)

Will it ever be the case that data is lost due to race condition between threads

EDIT: I have referred to link Are lists thread-safe , however …

python multithreading

5
推荐指数
1
解决办法
5621
查看次数

Python多线程列表追加

我想测试是否可以从两个线程追加到列表,但是输出混乱:

import threading


class myThread(threading.Thread):
    def __init__(self, name, alist):
        threading.Thread.__init__(self)
        self.alist = alist

    def run(self):
        print "Starting " + self.name
        append_to_list(self.alist, 2)
        print "Exiting " + self.name
        print self.alist


def append_to_list(alist, counter):
    while counter:
        alist.append(alist[-1]+1)
        counter -= 1

alist = [1, 2]
# Create new threads
thread1 = myThread("Thread-1", alist)
thread2 = myThread("Thread-2", alist)

# Start new Threads
thread1.start()
thread2.start()

print "Exiting Main Thread"
print alist
Run Code Online (Sandbox Code Playgroud)

所以输出是:

Starting Thread-1
Exiting Thread-1
 Starting Thread-2
 Exiting Main Thread
Exiting Thread-2
[1[1, 2[, …
Run Code Online (Sandbox Code Playgroud)

python multithreading

4
推荐指数
2
解决办法
1万
查看次数

这个python代码线程是否安全(带扭曲的线程)?

我正在编写一个应用程序来收集UDP消息并每1秒处理一次.

应用程序原型如下:

from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
import threading
import time

class UdpListener(DatagramProtocol):

    messages = []

    def datagramReceived(self, data, (host, port)):
        self.messages.append(data)

class Messenger(threading.Thread):

    listener = None

    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        while True:
            time.sleep(1)
            recivedMessages = self.listener.messages
            length = len(recivedMessages)
            messagesToProccess = recivedMessages[0:length]
            #doSomethingWithMessages(messagesToProccess)
            del self.listener.messages[0:length]
            print(length)

listener = UdpListener()

messenger = Messenger()
messenger.listener = listener
messenger.start()

reactor.listenUDP(5556, listener)
reactor.run()
Run Code Online (Sandbox Code Playgroud)

我不确定我是否可以轻松地从列表中删除起始值(del self.listener.messages [0:length]),而不会有任何传入消息更改列表和应用程序崩溃的风险.

更新 - 带锁的版本

class Messenger(threading.Thread):

listener = None
lock = threading.Lock()

def __init__(self): …
Run Code Online (Sandbox Code Playgroud)

python multithreading udp twisted

2
推荐指数
1
解决办法
1673
查看次数

当数据不断附加时,从python中的多个线程并发访问列表

我们有一个以固定时间间隔附加数据的列表,此过程需要时间,因此在写入期间使用通常的互斥锁来保护整个列表并不是最有效的解决方案。如何以更并发的方式组织对此类列表的读取和写入?

python multithreading list thread-safety

2
推荐指数
1
解决办法
4805
查看次数

这种Python线程的使用安全/好吗?

我有一个应用程序从某些网址获得一些结果,然后必须根据结果做出决定(即:选择最佳结果并将其显示给用户).由于我想查看几个网址,这是第一次非常需要多线程.

所以在一些例子的帮助下,我编写了以下测试代码:

import threading
import urllib2

threadsList = []
theResultList = []

def get_url(url):
    result = urllib2.urlopen(url).read()
    theResultList.append(result[0:10])

theUrls = ['http://google.com', ' http://yahoo.com']

for u in theUrls:
    t = threading.Thread(target=get_url, args=(u,))
    threadsList.append(t)
    t.start()
    t.join()

print theResultList
Run Code Online (Sandbox Code Playgroud)

这似乎有效,但我真的很不安全,因为我真的没有多线程的经验.我总是听到这些术语,如"线程安全"和"竞争条件".

当然我读到了这些东西,但由于这是我第一次使用这样的东西,我的问题是:这样做可以吗?我忽略了任何负面或意外的影响吗?有办法改善这个吗?

欢迎所有提示!

python multithreading

0
推荐指数
1
解决办法
84
查看次数