简体   繁体   中英

Python list syntax help

results=[key for key, value in adictionary if str(key).startswith('target') 
    and value > 0 ]

What am I trying to do here is select all the keys if the key in dictionary that beginswith target and its value is greater than 0. But looks there's a problem with this, help me~

results=[key for key, value in adictionary.items() if str(key).startswith('target') 
             and value > 0 ]

Missing items() ior iteritems() to your dict access. iteritems will not create a temp list which could be slightly faster.

results=[key for key, value in adictionary.iteritems() if str(key).startswith('target') 
             and value > 0 ]

您需要使用items()方法来获取键和值。

 [key for key, value in adictionary.items() if str(key).startswith('target') and value > 0]

I'd use the iteritems() method of the dictionary. It returns an interator rather than generating a full list like the items() method does.

results = [key for key, value in adictionary.iteritems() if str(key).startswith('target') and value > 0]

startswith() is slower than slicing

I would do:

results=[k for k,v in adictionary.iteritems()
         if (k[0:7]=='target')==True==(v>0)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM