Python-2-1 How to filter data in lists, dictionaries, and collections based on criteria-list resolution-filter__python

Source: Internet
Author: User
Tags iterable

2-1 How to filter data in lists, dictionaries, and collections based on criteria

Preliminary knowledge:
In this section we will use the Randint,lambda,timeit,filter and other keywords
The usual practice is to iterate through the current list and then place the element in the list that satisfies the condition in another list
From random import Randint
Randint (A,B) return random the integer in range [A, b], including both end points. use of the Timeit function Timeit.timeit (' func () ', ' func domain ', func how many times to execute, 1 million times by default)

From Timeit import Timeit
print Timeit (' Filter (lambda x:x > 0, [1,3,-5,5,3,3,3,3,3,33,1,2,3,4,5,5,5,5,5,2]) ', number=1)
Print Timeit (' [x for x in [1,3,-5,5,3,3,3,3,3,33,1,2,3,4,5,5,5,5,5,2] if x >0] ', number=1)
print Timeit (' Filter (lambda x:x > 0, DataList) ', setup= ' from __main__ import DataList ', Number=1]
print Timeit (' [X for X I n DataList if X >0] ', setup= ' from __main__ import DataList ', Number=1)

T3=timer ("Test3 ()", "from __main__ import tes T3 ")
print T3.timeit (1000000)
or
print Timeit (' [x for x in [1,3,-5,5,3,3,3,3,3,33,1,2,3,4,5,5,5,5,5,2] if x >0] ')

Solution:

List:

Randint is a function on both sides of the closed range. Rand ( -10,10) represents the resulting random number between 10 and 10, which includes-10, 102 endpoints generate a random list [Randint ( -10,10) for _ in range (10)] method one: List iterations Res=[] for x in Datalist:if x >= 0:res.append (x) method Two: list resolution [expr for Iter_var in iterable] The key is this for, iteration All entries for the Iterable object, the preceding expr applied to each member of the sequence, and the final result is the list produced by the expression [x for X in DataList if X>=0] [(x * * 2) for x in Xrange (6)] ===&gt  ; Map (lambda x:x **2, xrange (6)] [expr for Iter_var in iterable if conf_expr] #可以支持多重for loop Multiple IF statements (expr for Iter_var in   

iterable if conf_expr) #生成器表达式 use the Builder to save memory F = open (' Test.txt ', ' R ') Len ([Word for line in F for word in line.split ()]) SUM (len (word) for line in F of Word in line.split ()) Max (Len (X.strip ()) to X in open (' Test.txt ')) method three: Filter letter  Number of filter (...) #filter函数中的函数的返回类型是bool型的 Filter (function or None, sequence)-> list, tuple, or string return those items of s  Equence for which function (item) is true.  The If function is None and return the items that are true. If sequence is a tuple oR string, return the same type, else return a list. 
def func (x): if x > ' t ': return x filter (lambda x:x>=0,datalist) filter (lambda x:x >= ' t ', ' strxxx ') Filter (None, ' strxxx ') filter (func, ' strxxx ') filter (lambda x:x >4,tuple1) help (map) Help on built-in function map
    In module __builtin__: Map (...) map is used to quickly generate a list, functions in the function is an expression, for the given list to perform a certain operation, if you encounter the following list of groups to pass in, map will try to put this several seq together Map (function, sequence[, sequence, ...])-> list return a list of the results of applying the function to the ITE  Ms of the argument sequence (s). If more than one sequence are given, the function is called with a argument list consisting of the corresponding I  TEM of each sequence, substituting None for missing values as not all sequences have the same length.

If the function is None, return a list of the items of the sequence (or a list of tuples if more than one sequence). Map (Lambda x,y,z:str (x) + str (y) +str (z), (' xxx ', ' yyyzzz '), (' 123 ', ' 456'), (' abc ', ' Def ')] ==>[' xxx123abc ', ' yyyzzz456def '] ==>str1 = map (lambda h:h.replace (', '), str1) str1 =["AA", "BB  ", C C", "D d", "E E"] str1 = map (lambda h:h.replace (', '), str1) print str1 [' AA ', ' BB ', ' cc ', ' dd ', ' ee '] >>> Help (reduce) Help on built-in function reduce in module __builtin__: Reduce (...) #reduce从sequence中取出两个元素, take this two element as result 1, and then take The third element, the result 1 and the third element will result in 2, so that all the elements in the list, reduce (function, sequence[, initial])-> value Apply a function of two AR
    Guments cumulatively to the "a" sequence, from left to right, so as to reduce the sequence to a single value.  For example, reduce (lambda x, Y:x+y, [1, 2, 3, 4, 5]) calculates ((((1+2) +3) +4). If Initial is present, it is placed before the items to the sequence in the calculation, and serves as a default

The sequence is empty. >>> Reduce (lambda a,b:a&b,map (DICT.VIEWKEYS,[DICT1,DICT2,DICT3)) #取出三个字典中的key的交集, note that map is also used in print Reduce (Func,map (Dict.viewkeys,[DICT1,DICT2,DICT3]) Print reduce (lambda x,y:x + y,[1,2,3,4,5]) #reduce (lambda x, Y:x+y, [1, 2, 3, 4, 5]) calculates (((((1+2) +3) +4) +5)
Import time Import Timeit the random import randint #通过迭代遍历列表的方式 datalist = [Randint ( -10,10) for _ in Xrange (a)] R Es=[] for x in Datalist:if x >=0:res.append (x) Print res #filter function Res2 = filter (lambda x:x ; 0,datalist) Print Res2 #list list resolution print [X for X in DataList if x >0] #匿名函数和列表解析的比较 list resolution faster #timeit函数的用法 from Tim EIT Import Timeit Print Timeit (' Filter (lambda x:x > 0, [1,3,-5,5,3,3,3,3,3,33,1,2,3,4,5,5,5,5,5,2]) ', number=1) print Timeit (' [X for X ' [1,3,-5,5,3,3,3,3,3,33,1,2,3,4,5,5,5,5,5,2] if x >0] ', number=1) print Timeit (' Filter (Lambda x:x & Gt  0, DataList) ', setup= ' from __main__ import DataList ', number=1) print Timeit (' [X to X in DataList if X >0] ', setup= ' from __main__ import DataList ', Number=1) ' Dictionary filter ' Dict1={x:randint (60,100) for x in Xrange (20014540,20014550)} print D Ict1 Print {k:v for k,v in Dict1.iteritems () if v >80} ' filter set ' Set1=set (DataList) print {x for x in Set1 if x%3 ==0}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.