Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python字典中选择以相同字母开头的ID_Python_Python 3.x_Dictionary - Fatal编程技术网

在python字典中选择以相同字母开头的ID

在python字典中选择以相同字母开头的ID,python,python-3.x,dictionary,Python,Python 3.x,Dictionary,我有一本有名字和年龄的字典: classmates = {'Anne':15, 'Laura':17, 'Michel':16, 'Lee':15, 'Mick':17, 'Liz':16} 我想选择所有带有字母“L”的名称。我可以这样做: for name, age in classmates.items(): if "L" in name: print(name) 或 当我有数以百万计的条目并且需要重复操作数百万次时,有没有更有效的方法呢?一行代码列表理解 [ k

我有一本有名字和年龄的字典:

classmates = {'Anne':15, 'Laura':17, 'Michel':16, 'Lee':15, 'Mick':17, 'Liz':16}
我想选择所有带有字母“L”的名称。我可以这样做:

for name, age in classmates.items():
    if "L" in name:
        print(name)


当我有数以百万计的条目并且需要重复操作数百万次时,有没有更有效的方法呢?

一行代码
列表理解

[ key for key in classmates.keys() if key.startswith('L') ]
#驱动程序值
正如其他人所指出的,使用
startswith
而不是
中的
来查找字符是否在开头。

除非使用某种并行计算,否则搜索时间不会有任何性能。您可以使用@Kaushnik NP在过滤多个进程上分割的数据块时提到的过滤功能。
因此,您必须将字典拆分为4个较小的字典(取决于处理器的内核数量),在每个块上运行一个工作程序,并将您的公共数据存储在某个位置。
下面是一个片段,它使用多处理python库和队列来安排一些工作并存储该工作的结果:

#!/usr/bin/env python
import multiprocessing, os, signal, time, Queue

def do_work():
    print 'Work Started: %d' % os.getpid()
    time.sleep(2)
    return 'Success'

def manual_function(job_queue, result_queue):
    signal.signal(signal.SIGINT, signal.SIG_IGN)
    while not job_queue.empty():
        try:
            job = job_queue.get(block=False)
            result_queue.put(do_work())
        except Queue.Empty:
            pass
        #except KeyboardInterrupt: pass

def main():
    job_queue = multiprocessing.Queue()
    result_queue = multiprocessing.Queue()

    for i in range(6):
        job_queue.put(None)

    workers = []
    for i in range(3):
        tmp = multiprocessing.Process(target=manual_function,
                                      args=(job_queue, result_queue))
        tmp.start()
        workers.append(tmp)

    try:
        for worker in workers:
            worker.join()
    except KeyboardInterrupt:
        print 'parent received ctrl-c'
        for worker in workers:
            worker.terminate()
            worker.join()

    while not result_queue.empty():
        print result_queue.get(block=False)

if __name__ == "__main__":
    main()

有关该主题的其他示例,请参见不要在名称中使用
“L”
,它会在整个名称中搜索
“L”
。相反,请使用
name.startswith(“L”)
,它只会查看名称的开头。确实,我可以使用
name.startswith(“L”)
,但这种方法的速度有多快?@aLbAc取决于您拥有的数据量。就算法复杂性而言,在您的例子中,
startswith
是常数时间,而
中的
是线性时间。另外,
startswith
是更正确的方法,因为你只关心某件事是否以字母开头。我不明白
。。。或者key.startswith('I')
在这种情况下很有用,如果我只想要以“L”开头的单词。…@aLbAc,您之前的编辑使它看起来像是需要以
L
I
开头的单词。自从上次编辑以来,我已经更改了它。Kaushik NP right,我明白你的意思,我修改了它。
key.startswith('L')
key[0]==“L”
在性能方面的比较如何?另外,尝试
[key for key in classes.key()…
-我们对这些值不感兴趣,所以不要处理它们。
In : classmates = {'Anne':15, 'Laura':17, 'Michel':16, 'Lee':15, 'Mick':17, 'Liz':16}
Out : ['Lee', 'Liz', 'Laura']
#!/usr/bin/env python
import multiprocessing, os, signal, time, Queue

def do_work():
    print 'Work Started: %d' % os.getpid()
    time.sleep(2)
    return 'Success'

def manual_function(job_queue, result_queue):
    signal.signal(signal.SIGINT, signal.SIG_IGN)
    while not job_queue.empty():
        try:
            job = job_queue.get(block=False)
            result_queue.put(do_work())
        except Queue.Empty:
            pass
        #except KeyboardInterrupt: pass

def main():
    job_queue = multiprocessing.Queue()
    result_queue = multiprocessing.Queue()

    for i in range(6):
        job_queue.put(None)

    workers = []
    for i in range(3):
        tmp = multiprocessing.Process(target=manual_function,
                                      args=(job_queue, result_queue))
        tmp.start()
        workers.append(tmp)

    try:
        for worker in workers:
            worker.join()
    except KeyboardInterrupt:
        print 'parent received ctrl-c'
        for worker in workers:
            worker.terminate()
            worker.join()

    while not result_queue.empty():
        print result_queue.get(block=False)

if __name__ == "__main__":
    main()