1. Extract non-repeated data from the array
>>> A = [x * 2 for X in range (1, 5)] * 2
>>> Uniq = List (SET ())
[8, 2, 4, 6]
>>> Uniq = sorted (SET ())
[2, 4, 6, 8]
>>> B = {}
>>> For X in:
... B [x] = 1
>>> Uniq = B. Keys ()
2. Remove elements from another Array
>>> A = [x * 2 for X in range (1, 5)]
>>> B = [X for X in a if x> 3]
>>> Aonly = [X for X in a if x not in B]
>>> A_set = set ()
>>> B _set = set (B)
>>> Aonly = List (a_set-B _set)
3. array sorting
>>> Def comp (x, y ):
... If X> Y:
... Return-1
... Elif x = Y:
... Return 0
... Else:
... Return 1
>>> Unsorted_list = [82, 67, 10, 46, 81, 40, 71, 88, 55]
>>> Unsorted_list.sort (COMP)
[88, 82, 81, 71, 67, 55, 46, 40, 10]
4. intersection and operation of two Arrays
>>> A = [x * 2 for X in range (1, 5)]
[2, 4, 6, 8]
>>> B = [X for X in range (3, 7)]
[3, 4, 5, 6]
>>> A_set = set ()
>>> B _set = set (B)
# Union
>>> Print list (a_set | B _set)
[2, 3, 4, 5, 6, 8]
# Intersection
>>> Print list (a_set & B _set)
[4, 6]
# Difference
>>> Print list (a_set ^ B _set)
[8, 2, 3, 5]
5. array functions map (), filter (), reduce ()
A) map ()
Map (function, sequence) calls function (item) for each sequence element and forms an array of returned values.
>>>
>>> Def fun (x): Return x * x
>>> Print map (fun, range (0, 5 ))
[0, 1, 4, 9, 16]
Map (none, list1, list2) can be used to quickly convert two arrays into an array of element pairs.
>>> Print map (none, range (100,105), range ))
[(0,100), (1,101), (2,102), (3,103), (4,104)]
B) filter ()
Filter (function, sequence) returns a sequence that contains all elements that call function (item) and return true.
>>> Unsorted_list = [82, 67, 10, 46, 81, 40, 71, 88, 55]
>>> Def fun (x): Return X % 2 = 0
>>> Print filter (fun, unsorted_list)
[88, 82, 46, 40, 10]
C) reduce ()
Reduce (function, sequence) returns a single value. It first calls the function with the first two elements of the array, and then runs the function with the return value and the third element as the parameter.
For exampleProgramCalculate the sum of integers 1 to 10
>>> Def add (x, y): Return x + y
>>> Print reduce (ADD, range (0, 11 ))
55