Python's Common Builtins__python

Source: Internet
Author: User
Tags iterable

Divided into class and function

1. Class
1.1 Class Range

Help (__builtins__.range)
Class Range (object)
| Range (stop)-> Range object
| Range (start, stop[, step])-> Range Object
| Return a sequence of numbers from start to stop by step.
We usually use range in the For loop, but the range here is a class rather than a function
The python3.x range replaces the xrange, from the original built-in function into the class

For NUM in range (4):
    print (num, end = ')
Output

1.2 class Filter
Class Filter (object)
| Filter (function or None, iterable)--> Filter Object
| Return a iterator yielding those items of iterable for which function (item)
| Is true. The If function is None and return the items that are true.
values = [' 1 ', ' 2 ', '-3 ', '-', ' 4 ', ' N/A ', ' 5 ']
def is_int (val):
    try:
        if Int (val): Return
            True
    except ValueError: Return
        False
ivals = List (filter (Is_int, values))
print (ivals)
Output

[' 1 ', ' 2 ', '-3 ', ' 4 ', ' 5 ']

1.3 Class Enumerate
Class Enumerate (object)
| Enumerate (iterable[, start])-> iterator for index, value of iterable
|
|  Return an enumerate object. Iterable must be another object that supports
|  Iteration. The enumerate object yields pairs containing a count (from
| Start, which defaults to zero) and a value yielded by the iterable argument.
| Enumerate is useful to obtaining an indexed list:
| (0, Seq[0]), (1, seq[1]), (2, seq[2]), ...

s = ' Abcdefghijk ' for
(Index,char) in enumerate (s):
    print (str (index). Center (2), end = ')
    print (char)
Output

0  a
1  b
2  c
3  D
4  e
5  F
6  G
7  H
8  I
9  J
K
1.4 class Zip (object)
| Zip (iter1 [, Iter2 [...]])--> Zip object
|
| Return a Zip object whose. __next__ () method returns a tuple where
|  The i-th element comes from the i-th iterable argument. The. __next__ ()
| Method continues until the shortest iterable in the argument sequence
| is exhausted and then it raises stopiteration.
1.4.1
General Application

#列表以及迭代器的压缩和解压缩
ta = [1,2,3]
TB = [9,8,7]
TC = [' A ', ' B ', ' C '] for
(a,b,c) in Zip (TA,TB,TC):
    print (A, B,C)

# cluster
# zipped is a generator
zipped = Zip (ta,tb
) print (zipped)

# decompose
na, NB = Zip (*zipped)
print (Na, NB)
Output

1 9 A
2 8 B
3 7 C
<zip object at 0x00000000023cdec8>
<class ' Zip ' > (1, 2, 3
) (9, 8, 7)
1.4.2
List of adjacent element compressors

Zip (*[iter (s)]*n) application
How does Zip (*[iter (s)]*n) work in Python?
Explanation 1:
ITER () is a iterator over a sequence. [x] * n produces a list containing n quantity of x, i.e. a list of length n,
where each of the element is X. *arg unpacks a sequence into arguments for a function call.
Therefore you ' re passing the same iterator 3 times to zip (), and it pulls a item from the iterator.
Explanation 2:
ITER (s) returns an iterator for S.
[ITER (s)]*n makes a list of n times the same iterator for S.
So, when doing zip (*[iter (s)]*n), it extracts a item from all three iterators to the list in order.
Since the iterators are the same object, it just groups the list in chunks of N.

Example1:

s = [1,2,3,4,5,6,7,8,9]
n = 3

zz = Zip (*[iter (s)]*n) # returns [(1,2,3), (4,5,6), (7,8,9)] for
i in ZZ:
    prin T (i)
Output

(1, 2, 3)
(4, 5, 6)
(7, 8, 9)
Example2:

x = ITER ([1,2,3,4,5,6,7,8,9]) for
i in Zip (x, x, x):
    print (i)
Output

(1, 2, 3)
(4, 5, 6)
(7, 8, 9)
1.4.3
For the extension above

One word of advice for using the zip like 1.4.2. It would truncate your list if it ' s length is not evenly divisible.
You are could use something like this:
def n_split (iterable, N):
    Num_extra = Len (iterable)% n
    zipped = Zip (*[iter (iterable)] * N) return
    list (Zippe D) If not Num_extra else List (zipped) + n_split (Iterable[-num_extra:],num_extra)

for INTs in N_split (range (1,12), 3):
    print (', '. Join ([STR (i) for I in INTs])
Output

1, 2, 3
4, 5, 6 7,
8, 9
10, 11
Note:
A. Return on the N_split function on the post is return zipped if not num_extra else zipped + [Iterable[-num_extra:],],
But this will be an error typeerror:unsupported operand type (s) for +: ' Zip ' and ' list ', so eventually modified to the above form.
B.print (', '. Join ([STR (i) for I in INTs])) I must be in str form, or I'll make an error.
1.4.4 for the row-and-column interchange of two-dimensional matrices
A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
b = Map (List,zip (*a)) for
I in B:
    print (i)
Output

[1, 4, 7]
[2, 5, 8]
[3, 6, 9]
1.4.5 Inversion Dictionary
m = {' A ': 1, ' B ': 2, ' C ': 3, ' d ': 4}
Print (Dict (Zip (m.values (), M.keys ()))
Output

{1: ' A ', 2: ' B ', 3: ' C ', 4: ' d '}
1.5 class Map
Class Map (object)
| Map (func, *iterables)--> Map Object
|
| Make a iterator that computes the function using arguments from
|  Each of the iterables. Stops the shortest iterable is exhausted.
Re = map (lambda x,y:x+y), [1,2,3],[6,7,9]) for
i in Re:
    print (i)
Output

7
9
12
1.6 Class Slice
Class Slice (object)
| Slice (stop)
| Slice (start, stop[, step)
|
|  Create a Slice object. This is used for extended slicing (e.g. a[0:10:2]).
|
| Methods defined here:
| Indices (...)
| S.indices (len)-> (Start, stop, Stride)
|
| Assuming a sequence of length Len, calculate the start and stop
| indices, and the stride length of the extended slice described by
| S. Out of bounds indices are clipped in a manner consistent with the
| Handling of normal slices.
| Data descriptors defined here:
| Start
| Step
| Stop
#命名列表切割方式
A = [0, 1, 2, 3, 4, 5]
ind = Slice ( -3, None)
print (A[ind]) for 
I in Ind.indices (6):
    print (i)  
print (a[3:6:1])
#由上脚本可知indices其实就是对slice的一种解释, in fact, slice ( -3, None) into slice (3,6,1) The result is the same
Output

[3, 4, 5]
3
6
1
[3, 4, 5]

2. Built-in functions:
2.1 Built-in function Iter

ITER (...)
ITER (iterable)-> iterator
ITER (callable, Sentinel)-> iterator

Get a iterator from object. In the argument must
Supply its own iterator, or being a sequence.
In the second form, the callable is called until it returns the Sentinel.
For I on ITER (range (5)):
    print (i, end = ')
Output

0 1 2 3 4
2.2 built-in function min
Min (...)
Min (iterable, *[, Default=obj, Key=func])-> value
Min (arg1, arg2, *args, *[, Key=func])-> value

With a single iterable argument, return to its smallest item. The
Default Keyword-only argument specifies an object to return if
The provided iterable is empty.
With two or more arguments, return the smallest argument.
# for the tow methods, we give the examples, as follows:
# Data reduction across fields of a data structure
PORTFO Lio = [
   {' name ': ' GOOG ', ' shares ': +},
   {' name ': ' YHOO ', ' shares ': ' {'
   name ': ' AOL ', ' shares ':},
   {' Name ': ' Scox ', ' shares ': '
print (min (p[' shares ' for p in portfolio))
print (min (portfolio, key = lambda x : x[' shares '])
Output

{' name ': ' AOL ', ' shares ': 20}
2.3 Help on built-in function eval
Eval (...)
Eval (source[, globals[, locals]])-> value

Evaluate the source in the context of globals and locals.
The source may be a string representing a Python expression
Or a code object as returned by compile ().
The globals must be a dictionary and locals can is any mapping,
Defaulting to the current globals and locals.
If only globals are given, locals defaults to it.
The eval () function is powerful, as the official demo explains: String STR is evaluated as a valid expression and returns the result of the calculation. So, combining math is good for a calculator.
Other uses, you can convert list,tuple,dict and string into each other. See the following example:
>>> a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
>>> print (Type (eval (a))
<class ' list ' >
Another example:

# Compute area with console input
import Math
# Prompt The user to enter a radius
radius = eval (Input ("Enter a  Value for radius:]
# Compute area Area
= Pow (RADIUS, 2) * Math.PI
# Display results
print ("the The circle of radius ", radius," is ", area)


Related Article

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.