2017-10-11 84 views
0

开始选择IDS我有姓名和年龄的字典:具有相同字母的Python字典

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) 

Lnames = [name for name in classmates.items() if "L" in name] 

有没有当我有上百万个条目的,我需要重复操作上百万次做的更有效的方法?

+1

看看['str.startswith '](https://docs.python.org/3/library/stdtypes.html#str.startswith) – PRMoureu

+3

不要在名称中使用''L',它会搜索整个名称为''L''。相反,使用'name.startswith(“L”)'这将只是看名字的开始。 –

+0

true,我可以使用'name.startswith(“L”)',但这种方法快多少? – aLbAc

回答

1

一个衬垫List Comprehension

[ key for key in classmates.keys() if key.startswith('L') ] 

#driver值

In : classmates = {'Anne':15, 'Laura':17, 'Michel':16, 'Lee':15, 'Mick':17, 'Liz':16} 
Out : ['Lee', 'Liz', 'Laura'] 

正如其他人所指出的,用的,而不是startswithin找到字符是否出现在开头。

+0

我不明白'...'或key.startswith('I')在这种情况下是有用的,如果我只想要那些以“L”开头的... – aLbAc

+0

@aLbAc,您之前的编辑使它看起来你需要用'L'和'I'开始的两个单词。自上次编辑以来已更改它。 –

+0

Kaushik NP的权利,我明白你的意思,我修改了。 – aLbAc

0

在您使用某种并行计算之前,搜索时间不会有任何性能。您可以使用@Kaushnik NP提到的过滤来过滤几个进程上的分割块数据。
因此,您必须将字典拆分为4个较小的字典(取决于处理器的核心数量),在每个块上运行一个工作程序并将公用数据存储在某处。
下面是一个使用多蟒蛇lib和队列调度一些工作和存储工作成果的一个片段:

#!/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() 

有关该主题的其他例子,use that link

相关问题